Important Array Methods in JavaScript

Important Array Methods in JavaScript

Arrays in JS are Dynamic, i.e., They can be changed during the time of execution. They can store more than one Data Type (Unlike Java and C++ where we have to declare an array beforehand and specify the size and the data type like strings or integers). To make changes in the array we have some methods provided by JavaScript which are quite useful when it comes to performing operations on the array. Let's Study these methods.


Array.push()

  • Adds an Element to the end of the array
let arr = [1, 2, 3]
arr.push(4)
console.log(arr)
// [1, 2, 3, 4]
  • Returns the new length of the array
let arr = [1, 2, 3]
let length = arr.push(4);
console.log(length)
// 4
  • Array.push() can be used to push multiple elements into the array
let arr = ['element1', 'element2', 'element3']
let returnVal = arr.push('element4', 'element5', 'element6')
console.log(arr, returnVal) 
// [ 'element1', 'element2', 'element3', 'element4', 'element5', 'element6' ] 6

Array.unshift()

  • Array.unshift() also have the same behaviour as Array.push() except it gets applied to the start of the array
let arr = [1, 2, 3, 4];
let returnVal = arr.unshift(5, 6, 7)
console.log(arr, returnVal)
// [ 5, 6, 7, 1, 2, 3, 4 ] 7

Array.pop()

  • This method removes an element from the end of the array and returns the popped value

  • Note: This method does not accept any Parameter

let plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
let poppedPlant = plants.pop();
console.log(poppedPlant, plants);
// output: "tomato" ["broccoli", "cauliflower", "cabbage", "kale"]

Array.shift()

  • This method is exactly similar to Array.pop() except it removes an element from the beginning of the array
let plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
let shiftedPlant = plants.shift();
console.log(shiftedPlant, plants);
// output: "broccoli" ["cauliflower", "cabbage", "kale", "tomato"]

Array.concat()

  • Array.concat() can be used to merge two or more arrays.

  • This method does not modifies the original array but instead, it creates a new array with a different memory location.

  • This method accepts at least one parameter.

  • The array that is to be concatenated should be passed as a parameter.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);

console.log(array3);
// ["a", "b", "c", "d", "e", "f"]


const array4 = ['a', 'b', 'c'];
const array5 = ['d', 'e', 'f'];
const array6 = array2.concat(array1);

console.log(array6);
// ["d", "e", "f", "a", "b", "c"]

Array.slice()

  • Array.slice() slices the array from a particular start to end (not included) and returns a shallow copy of the array.

  • Shallow Copy: The sliced part will point to the same memory location as the original object elements. So, Any changes in the original array will also affect the sliced part.

  • It does not modify the original array but returns a value itself.

  • It accepts one (start only) or two (start and end) parameter. In case of one parameter, the end will be considered by default as the total length of the array.

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

Array.indexOf()

  • The indexOf() method of Array instances returns the first index at which a given element can be found in the array, or -1 if it is not present.
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

Array.join()

  • The join() method of Array instances creates and returns a new string by concatenating all of the elements in this array, separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

  • It does not modify the original array

const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// "Fire,Air, Water"

console.log(elements.join(''));
// "FireAirWater"

console.log(elements.join('-'));
// "Fire-Air-Water"

console.log(elements)
//  Array ["Fire", "Air", "Water"]

Array.reverse()

  • The reverse() method of Array instances reverses an array in place and returns the reference to the same array, the first array element now becoming the last, and the last array element becoming the first. In other words, elements order in the array will be turned towards the direction opposite to that previously stated.
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// Expected output: "array1:" Array ["one", "two", "three"]

const reversed = array1.reverse();
console.log('reversed:', reversed);
// Expected output: "reversed:" Array ["three", "two", "one"]

// Careful: reverse is destructive -- it changes the original array.
console.log('array1:', array1);
// Expected output: "array1:" Array ["three", "two", "one"]
  • To reverse the elements in an array without mutating the original array, use toReversed().
let arr = [1, 12, 133, 34]
arr.toReversed()
console.log(arr)
// > Array [1, 12, 133, 34]

const newer = arr.Reversed()
console.log(newer)
// > Array [34, 133, 12, 1]

Array.splice()

  • Array.splice() removes the elements from an array in-place which means it modifies the original array.

  • Splice() can be used if we want to delete/replace a particular number of elements from a particular index.

  • Parameters: startingIndex, deleteCount (optional, if not specified it will delete or replace all the elements from startingIndex to the end), itemsToReplace

const months = ['Jan', 'Feb', 'march', 'April'];
months.splice(0)
console.log(months)
// []
const months = ['Jan', 'Feb', 'march', 'April'];
months.splice(2)
console.log(months)
// [ 'Jan', 'Feb' ]
const months = ['Jan', 'Feb', 'march', 'April'];
months.splice(2, 1)
console.log(months)
// [ 'jan', 'feb', 'april' ]
const months = ['Jan', 'Feb', 'march', 'April'];
months.splice(2, 2, 'may', 'June')
console.log(months)
// [ 'jan', 'feb', 'may', 'june' ]
const months = ['Jan', 'Feb', 'march', 'April'];
months.splice(1, 3, 'may', 'June')
console.log(months)
// [ 'jan', 'may', 'june' ]
  • To create a new array with a segment removed and/or replaced without mutating the original array, use toSpliced(). It will return a spliced copy of the original array instead of modifying it in-place.
const months = ['Jan', 'Feb', 'march', 'April'];
const splicedArr = months.toSpliced(1, 3, 'may', 'June')
console. log('Original Array: ', months, 'Spliced Array: ', splicedArr)
// Original Array:  [ 'Jan', 'Feb', 'march', 'April' ] Spliced Array:  [ 'Jan', 'may', 'June' ]