JS Array Methods Explained with Examples

JS Array Methods Explained with Examples

What is an Array?

An array is a data structure that contains a group of elements. Elements can be of any type, such as an integer or string. Arrays are commonly used to organize data, So that values can be easily accessed.

Indexing in Array

  • 0 (Zero Based Indexing)- The first element of the array refers to index 0.
  • 1 (One Based Indexing)- The first element of the array refers to index 1.

Creating an Array

JavaScript array syntax

const array_name = [item1, item2, ...];

Example:

const cities= ["Bengaluru", "Mumbai", "Delhi", # "Kolkata"];

Characteristics of Array

  • Arrays are resizable and can have any type.
  • They are indexed from zero.
  • Arrays allocate memory in contiguous memory locations for all its data elements.
  • Array elements can be accessed easily by using its index numbers

Useful Array methods and operations

  • splice()

    splice() method helps you add, update, and remove elements in an array. It returns an array of the elements deleted and modifies the original array.

Syntax:

array.splice(index, howmany, item1, ....., itemX)

Example:

const names = ['tom', 'alex', 'bob','adam','cam'];

console.log(names.splice(1, 2, 'zack'));//[ 'alex', 'bob' ]

console.log(names); // [ 'tom', 'zack', 'adam', 'cam' ]
  • slice()

Slice() is used to retrieve a specific range of an array elements. It returns a new array and does not change the original array. Here start & end denotes the index of elements of the array that needs to be retrieved where start index is included and end index is excluded.

Syntax:

slice() 
slice(start)
slice(start, end)  // end is not included

Example:

const groceryList= [ 'Apple', 'Mango', 'bananas', 'pineapple', 'strawberry' ];
console.log(groceryList.slice(2));        // ['bananas', 'pineapple', 'strawberry']
console.log(groceryList.slice(2, 4));        // ['bananas', 'pineapple']
console.log(groceryList.slice(1, 5));        // ['Mango', 'bananas', 'pineapple', 'strawberry' ]
console.log(groceryList.slice(-2));        // ['pineapple', 'strawberry']
console.log(groceryList.slice(2, -1));        // [ 'bananas', 'pineapple'].
  • concat()

concat() is used to merge two or more arrays. It does not change the original arrays but returns the new merged array.

Example:

const arrOne = ['A', 'B', 'C'];
const arrTwo = ['F', 'E', 'D'];
const arrThree=['G', 'H', 'I']
const arrFour = arrOne.concat(arrTwo);
const arrFive = arrOne.concat(arrTwo, arrThree)
console.log(arrFour);        // [ 'A', 'B', 'C', 'F', 'E', 'D' ]
console.log(arrFive);   //['A', 'B', 'C','F', 'E', 'D','G', 'H', 'I']
  • join()

join() method joins all the elements of an array with separator passed and returns a new string. When no separator argument is passed by default it uses comma (,).

Example :

const groceryList= [ 'Apple', 'Mango', 'bananas', 'pineapple', 'strawberry' ];
console.log(groceryList.join());        // Apple,Mango,bananas,pineapple,strawberry
console.log(groceryList.join(''));        // AppleMangobananaspineapplestrawberry
console.log(groceryList.join('_'));     //Apple-Mango-bananas-pineapple-strawberry
  • includes()

includes() method is used check if an element is present in an array or not. If the element is present then it will return true else it returns false.

Example:*

const groceryList= [ 'Apple', 'Mango', 'bananas', 'pineapple', 'strawberry' ];
console.log(groceryList.includes('Apple'));        // true
console.log(groceryList.includes('grappes'));        // false
  • indexOf(),

    lastIndexOf()

indexOf() method is used to find the index of an element in an array. If an element is not present then indexOf() method returns -1. If an element is present more than one time then the indexOf() method returns the index of its first occurrence of the element and lastindexOf returns last occurance of an element.

Example:

const groceryList= [ 'Apple', 'Mango', 'bananas', 'pineapple', 'strawberry','Mango' ];
console.log(groceryList.indexOf('Mango'));        //returns 1
console.log(groceryList.indexOf('graphes'));      //returns -1
console.log(groceryList.lastIndexOf('Mango'));    //returns 5
  • reverse()

reverse(): method reverses the index position of all the elements in the array. Original array elements will be modified on use of reverse.

Example:

const groceryList= [ 'Apple', 'Mango', 'bananas', 'pineapple', 'strawberry','Mango' ];
console.log(groceryList.reverse());        //[ 'Mango', 'strawberry', 'pineapple', 'bananas', 'Mango', 'Apple' ]
console.log(groceryList);                  //[ 'Mango', 'strawberry', 'pineapple', 'bananas', 'Mango', 'Apple' ]
  • sort()

sort() method converts all the elements of the array into a string and then sorts them in ascending order. Original array elements will be modified on use of sort.

Example:

const groceryList= [ 'Apple', 'mango', 'bananas', 'pineapple', 'strawberry','Mango' ];
console.log(groceryList.sort());        // returns [ 'Apple', 'Mango', 'bananas', 'mango', 'pineapple','strawberry']
console.log(groceryList);                  // returns [ 'Apple', 'Mango', 'bananas', 'mango', 'pineapple', 'strawberry']
  • push()

push() method is used to insert an element into an array. The push() method adds an element at the end of the array. Push methods returns length of array position.

Example:

const groceryList= [ 'Apple', 'mango', 'bananas', 'pineapple', ];
console.log(groceryList.push('graphs'));        // returns 5
console.log(groceryList);               // returns [ 'Apple', 'mango', 'bananas', 'pineapple', 'graphs' ]
  • unshift()

unshift() method is used to insert an element into an array. The unshift() method adds an element at the beginning of the array. unshift methods returns length of array position.

const groceryList= [ 'Apple', 'mango', 'bananas', 'pineapple', ];
console.log(groceryList.unshift('graphs'));        // returns 5 
console.log(groceryList);               // returns [ 'graphs', 'Apple', 'mango', 'bananas', 'pineapple' ]
  • pop()

pop() method removes an element from the end of the array. Then it returns the removed element and changes the original array.

Example:

const groceryList= [ 'Apple', 'mango', 'bananas', 'pineapple', ];
console.log(groceryList.pop());        // returns pineapple
console.log(groceryList);               // returns [  'Apple', 'mango', 'bananas' ]
  • shift()

shift() remove's an element from the beginning of an array. Like the pop() method, shift() returns the removed element and changes the original array.

Example:

const groceryList= [ 'Apple', 'mango', 'bananas', 'pineapple', ];
console.log(groceryList.shift());        // returns Apple
console.log(groceryList);               // returns [ 'mango', 'bananas', 'pineapple' ]