Photo by Fotis Fotopoulos on Unsplash
Javascript tips and tricks, Every JS developer must know
A quick guide to Javascript Arrays
Table of contents
An array is a collection of data elements, saved in a contiguous memory location. It is one of the simplest and most widely used data structures. It is one of the basic data structures that we learn in the initial stage of learning programming. In this article, I will be sharing some of my experiences and the best practices that we should use while using Javascript Arrays.
Mostly in my experience, whenever I have seen bad coding practices. They are mostly related to the arrays and their manipulation of data. I have seen many developers who are confused about when to use forEach
, for
, map
, reduce
, for...in
, for...of
loop. Some find difficulty in manipulating data, like filtering, and picking object values. So I will summarize all these basic javascript operators here and their best uses in this article. So let's get started
Permalink1. Remove duplicates from an array
This is the most popular asked javascript interview question about javascript arrays when someone asks to remove duplicates or find unique elements from an array.
Sets
should always come into your mind in the first go.
The Set object lets you store unique values of any type, whether primitive values or object references.
var numbers = [ 1, 3, 5, 2, 5, 7, 8, 1, 86, 33, 25, 5 ]
function findUnique(arrayWithDuplicates) {
return [...new Set(arrayWithDuplicates)]
}
// numbers = [ 1, 3, 5, 2, 5, 7, 8, 1, 86, 33, 25, 5 ]
findUnique(numbers)
// numbers = [1, 3, 5, 2, 7, 8, 86, 33, 25]
Permalink2. Generate an array with default values
There are certain situations in which a developer needs to have a default array size filled with some data. so some developers use a for
loop and push
method to insert data into an array, which is a bad practice. Instead, we can use a built-in Array constructor property to generate default values and a fill method to insert default values.
let n = 10 // length of an array
// method # 1
Array(n).fill(0)
Array(n).fill({ "name": "" })
// method # 2
Array.from({ length: n }, () => 0 )
Array.from({ length: n }, () => { "name": "" } )
// method # 3
Array.apply(null, Array(n)).map(() => 0)
Array.apply(null, Array(n)).map(() => { "name": "" })
Permalink3. Merging two arrays and de-duplicates items
Before es6 and the introduction to the spread operator, merging two arrays was quite messy and not straightforward, as it is now.
let array1 = [1,2,3]
let array2 = [1,2,3,4,5]
// method # 1 - es5 syntax
var combinedArray = array1.concat(array2) // [1, 2, 3, 1, 2, 3, 4, 5]
combinedArray.filter((item, pos) => combinedArray.indexOf(item) === pos)
// [1, 2, 3, 4, 5]
// method # 2 - es6 syntax
[...new Set([...array1 ,...array2])]
// [1, 2, 3, 4, 5]
Permalink4. Sorting an Integer array
Sometimes while doing a code review, I have seen some junior developers use only the .sort()
method to sort an integer array. which is absolutely incorrect because it will sort an array on the basis of asci characters. So the correct code shall be
var numArray = [ 10, 5, 8, 12, 23, 55, 99, 15 ];
numArray.sort((a, b) => a - b);
[5, 8, 10, 12, 15, 23, 55, 99]
numArray.sort((a, b) => b - a);
[99, 55, 23, 15, 12, 10, 8, 5]
Permalink5. Insert an element on a specific index in an array.
Sometimes, we need to add data in to an array on any specific index. there are many ways to do this, but the most preferred way I always use is using splice
or slice
.
const items = [1, 2, 3, 4, 5]
// method # 1
const insert = (arr, index, ...newItems) => [
...arr.slice(0, index),
...newItems,
...arr.slice(index)
]
insert(items, 1, 6)
// [1, 6, 2, 3, 4, 5]
// method # 2
items.splice(1, 0, 6)
// [1, 6, 2, 3, 4, 5]
Permalink6. Check if an array contains a certain item.
So, finding an element. if it exists in an array, is the most commonly used function in data-intensive applications. So now we will see how to find value from an array.
const items = [1, 2, 3, 4, 5, 3, 4, 5]
const itemToFind = 3
// method # 1
items.find((eachItem)=>{eachItem == itemToFind}) // 3
// method # 2
items.findIndex((eachItem)=>{eachItem == itemToFind}) // 2
// method # 3
items.indexOf(itemToFind) // 2
// method # 4
items.lastIndexOf(itemToFind) // 5
Permalink7. Remove certain elements from an array.
const items = [1, 2, 3, 4, 5, 3, 4, 5]
const removeItem = 5
// method # 1
items.filter(item => item !== removeItem)
PermalinkConclusion
In this article, I have presented you most commonly used operations with an array data structure. while keeping code short and clean. There are many other operations, that we use. Most importantly, some developers prefer using lodash
for these operations. So, stay tuned. I will be back with a new update related to lodash
and more javascript tips.
See ya! and keep happy coding.