One Stop For Array In JavaScript

One Stop For Array In JavaScript

This blog is part of the JavaScript series. Check out the complete series of JavaScript Here.

The array is the most important data structure in JavaScript. Many people find it difficult to understand the array and its methods. But in this blog, we will dive deep into an array and their methods one by one.

Frame 40.png

Push

push() method adds new items at end of an array.

let arr = [1,2,3,4];
console.log(arr); // [1,2,3,4]
arr.push(5);
console.log(arr); // [1,2,3,4,5]

Pop

Pop removes the last element from the original array.

let arr = [1,2,3,4,5];
let removed = arr.pop();
console.log(removed);  //  [1,2,3,4]

Shift

With the help of shift we can remove first element in array.

let arr = [1,2,3,4,5];
console.log(arr); // [1,2,3,4,5]
arr.shift();
console.log(arr);  //  [2,3,4,5]

Unshift

Unshift adds a new element at beginning of the array.

let arr = [1,2,3,4,5];
console.log(arr); // [1,2,3,4,5]
arr.unshift(99);
console.log(arr);  //  [99,2,3,4,5]

indexOf

indexOf gives the first index of element we want to search.

let arr = ['a','b','c','d'];
let index = arr.indexOf('b');
console.log(index);  //  1

includes

includes give true if the element is found and false if the element is not found.

let arr = [1,2,3,4,5];
let result1 = arr.includes(100);
let result2 = arr.includes(5);
console.log(result1); // false
console.log(result2); // true

We can also give an index number to start searching from the specified index.

let arr = [1,2,3,4,5];
let result1 = arr.includes(2,3);
let result2 = arr.includes(1,3);
console.log(result1); // false
console.log(result2); // false

Both 1 and 2 are present in array but we are searching from index 3 so it gives false.

Slice

Slice is the method of an array in JavaScript. The slice() method returns selected elements in an array, as a new array. The slice() method selects from a given start, up to a (not inclusive) given end.

  • The slice() method does not change the original array.

Example

let arr = [1,2,3,4,5];
let sliced = arr.slice(1,3);
console.log(sliced); // 2,3

We can also use a negative index in the slice.

let arr = [1,2,3,4,5];
let sliced = arr.slice(-1);
console.log(sliced); // 5

Splice

With the help of a splice, we can add or remove elements of an array.

  • Splice method overwrites the original array.
let arr = [1,2,3,4,5];
let spliced= arr.splice(0,2);
console.log(spliced); // 1,2
console.log(arr); // 1,2

From the above example, it's clear that when we splice an array it removes elements from the original array.

We will now see how to add elements in array using splice.

let arr = [1,2,3,4,5];
let spliced= arr.splice(0,2,"ES6","JavaScript");
console.log(spliced); // 1,2
console.log(arr); // "ES6","JavaScript",3,4,5

In the above example, the splice will remove elements at index 0 and 1 (because 2 is not inclusive) and replace them with given values.

Reverse

The reverse method reverses the order of the elements in an array.

  • The reverse() method overwrites the original array.
let ar1 = [1,2,3,4,5];
let ar2 = ['a','b','c','d','e'];
ar1.reverse();
ar2.reverse();
console.log(ar1); // 5,4,3,2,1
console.log(ar2); // e,d,c,b,a

Concat

The concat method joins two or more arrays. It returns a new array, containing the joined arrays.

  • The concat() method does not change the existing arrays.
let arr1 = [1,2,3,4];
let arr2 = [5,6,7,8];
let joinedArray = arr1.concat(arr2);
console.log(joinedArray); //1,2,3,4,5,6,7,8

Join

The join method returns an array as a string. Any separator can be specified. The default is comma (,).

  • The join() method does not change the original array.
let arr1 = ['a','b','c','d','e'];
let arr2 = [1,2,3,4,5];
let joined1 = arr1.join("");
let joined2 = arr2.join("");
console.log(joined1); // abcde
console.log(joined2); // 12345
console.log(typeof joined1); // string
console.log(typeof joined2); // string

forEach

The forEach() method calls a function for each element in an array. It is not executed for empty elements. We cannot use continue or break in forEach.

We can access element, index, and whole arrays in forEach. In forEach, we have a callback function in which we have to give 3 parameters, and the sequence of parameter matter a lot. First is the element, second is an index and third is a whole array itself. Let's try it using an example.

let arr = ['a','b','c','d','e'];
arr.forEach((ele,index,array) =>{
  console.log(`Element : ${ele}`);
  console.log(`Index: ${index}`);
  console.log(`Whole Array: ${array}`);
})

// 1st iteration
// Element: a
// Index: 0
// Whole Array: ['a','b','c','d','e']

// 2nd iteration
// Element: b
// Index: 1
// Whole Array: ['a','b','c','d','e']

forEach for map

We can use forEach for set and map as well. Let's take example to understand better.

let mp = new Map();
mp.set("Language","JavaScript");
mp.set("Age", 25);
mp.set("Year", 1995);

mp.forEach((value,key,map) =>{
  console.log(`Value: ${value}`);
  console.log(`Key: ${key}`);
  console.log(map);
});

// 1st iteration
// Value: JavaScript
// Key: Language
// Map {Language => JavaScript, Age => 25, Year => 1995}

// 2nditeration
// Value: 25
// Key: Age
// Map {Language => JavaScript, Age => 25, Year => 1995}

Data Transformation: map(),filter(),reduce()

map

map() creates a new array by calling a function for every array element. It calls a function once for each element in an array.

  • map() does not change the original array.

map.png

Example

// Square of each element
let arr = [1,2,3,4,5];
const newArray = arr.map((ele) =>{
  return ele * 2;
}
);
console.log(newArray); // 1,4,9,16,25

filter

The filter() method creates a new array filled with elements that pass a test provided by a function.

  • The filter() method does not change the original array.

filter.png

// Filter Even elements
let arr = [1,2,3,4,5];
const newArray = arr.filter((ele) =>{
  return ele % 2 == 0;
}
);
console.log(newArray); // 2,4

reduce

The reduce() method returns a single value: the function's accumulated result.

  • The reduce() method does not change the original array.

reduce.png

// Sum of all elements in array
let arr = [1,2,3,4,5];
const newArray = arr.reduce((total,current) =>{
  return total + current;
}
);
console.log(newArray); // 15

Method Chaining

Method Chaining is using the method on a method to simplify the use of the multiple methods on one object.

const arr = [1,2,3,4,5];

// Method Chaining
const result = arr.filter(ele => ele % 2 == 0)
.reduce((acc,curr) => acc+curr,0);

find

The find() method returns the value of the first element that passes a test. It executes a function for each array element. It returns undefined if no elements are found.

  • The find() method does not change the original array.
let trans = [121,-653,98,-88,-988,654,345,678,-22,-11,1232];
const result = trans.find(ele => ele < 0);
console.log(result);

findIndex

The findIndex() method returns the index (position) of the first element that passes a test. It returns -1 if no match is found.

  • The findIndex() method does not change the original array.
let arr = [1,2,-10,3,4,-200,-101,6,7,8];
const result = arr.findIndex((a) =>{ return a < 0 });
console.log(result); // 2

some

The some() method checks if any array elements pass a test (provided as a callback function). It executes the callback function once for each array element and returns true (and stops) if the function returns true for one of the array elements and returns false if the function returns false for all of the array elements.

  • The some() method does not change the original array.
let arr = [1,2,-110,32,-101,22,-11,-98,22,63,92,-99];
let result = arr.some(ele => ele < 0);
let result2 = arr.some(ele => ele > 0);
console.log(result); // true
console.log(result2); // false

every

The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements and returns false if the function returns false for one element.

  • The every() method does not change the original array
let arr = [1,2,-110,32,-101,22,-11,-98,22,63,92,-99];
let result = arr.every(ele => ele < 0);
let result2 = arr.every(ele => ele > 0);
let result3 = arr.every(ele => typeof ele == 'number');
console.log(result); // false
console.log(result2); // false
console.log(result3); // true

flat and flatMap

Both these features were introduced in ES2019

flat

The flat() method creates a new array by flattening a nested array up to the specified depth.

The flat() method takes a single parameter:

  • depth - Integer specifying how deep a nested array should be flattened. Its default value is 1.
let arr = [1,2,3,[4,5,6,[7,8,9]]];
console.log(arr.flat()); // [1,2,3,4,5,6,[7,8,9]];
console.log(arr.flat(2)); // [1,2,3,4,5,6,7,8,9];

flatMap

The flat map is a combination of flat and map methods. Using flat map we have to provide a callback function and after mapping, it flatters the array to a depth of 1. It cannot go beyond the depth of 1.

let arr = [1,2,[3,4],5,6,[7,8]];
let result = arr.flatMap(ele => ele );
console.log(result); // [1,2,3,4,5,6,7,8]

When to use which array method

Changing Original Array

  • Add to the original

    • push()
    • unshift()
  • Remove from original

    • pop()
    • shift()
    • splice()
  • Other methods

    • reverse()
    • sort()

New Array

  • Compute from original

    • map()
  • Filter using condition

    • filter()
  • part of original

    • slice()
  • concatenate 2 arrays

    • concat()
  • Flattening original

    • flat()
    • flatMap()

An Array Index

  • Value based

    • indexOf()
  • Based on condition

    • findIndex()

An Array Element

  • Based on condition
    • find()

To know if array includes

  • Value based

    • includes()
  • based on condition

    • some()
    • every()

To create new string

  • join()

To transform array to single value

  • reduce()

To loop array based on callback

  • forEach()

Did you find this article valuable?

Support Kedar Makode by becoming a sponsor. Any amount is appreciated!