JavaScript Array Handbook

JavaScript Array Handbook

Learn all about JavaScript arrays and its methods in single article

Hey folks, hope you all are doing well! In today's article, we're gonna discuss JavaScript array and it's methods.

Array Definition

A pair of square brackets[] that contains comma (,) separated elements, represents an Array.

JavaScript arrays can contain elements of different data types. They are heterogenous in nature.

const myArray = [ 1, "Bobby", true, [3, '4'],  { 'key' : value } ]

Position in an array, is known as index. Array index starts with "0".

Ways to create an array

  • Using Array Literals [ ]:

      const myArray = [ 1, '2', true ]
    
  • Using Array Constructor :

      const myArray = new Array(1, '2', true)  //  [1, '2', true]
    

Retrieve array elements

  • Using square bracket syntax [ ]

      const element = myArray[2]
    

JavaScript Methods

Insertion & Deletion

  • push(element) - It adds element at the end of an array and returns the new length of the array.

      const myArray = [ 1, 2, 3 ]
      myArray.push(4) // [ 1, 2, 3, 4 ]
    
  • unshift(element) - It adds element at the beginning of an array and returns the new length of the array.

      const myArray = [ 1, 2, 3 ]
      myArray.unshift(4) // [ 4, 1, 2, 3 ]
    
  • pop(element) - It removes last element of an array and returns that element.

      const myArray = [ 1, 2, 3, 4 ]
      myArray.pop(4) // [ 1, 2, 3 ]
    
  • shift(element) - It removes first element of an array and returns that element.

      const myArray = [ 1, 2, 3 ]
      myArray.shift(4) // [ 2, 3 ]
    
  • splice(start index, number of elements to be deleted, elements to be added)

    It is used to remove specified number of elements from a particular index and can also add other elements to that particular index.

    It returns an array of deleted elements.

      const myArray = [ 1, 2, 3, 4, 5 ]
      const deletedItems = myArray.splice(1, 2, 6)
    
      console.log(deletedItems) // [ 2, 3 ]
      console.log(myArray); // [ 1, 6, 4, 5 ]
    
  • fill(value, start, end)

    It fill all values of an array from a start index to end index. It overwrites the original array.

      const myArray = [ 1, 2, 3, 4, 5 ]
      myArray.fill( 0, 1, 4 )
    
      console.log(myArray); // [ 1, 0, 0, 0, 5 ]
    

Searching

  • indexof(element, start)

It returns first index of specified element. Returns -1 if not found.

Search starts at specified index from left to right. By default, search starts from left.

    const myArray = [ 1, 2, 3, 4, 5, 4 ]
    let myIndex = myArray.indexOf(4)

    console.log(myIndex); // 3
  • lastIndexof(element, start)

It returns last index of specified element. Returns -1 if not found.

Search starts at specified index from right to left. By default, search starts from right.

const myArray = [ 1, 2, 3, 4, 5, 4 ]
let myIndex = myArray.lastIndexOf(4)

console.log(myIndex); // 5
  • includes(element, start)

    It returns true if value found otherwise returns false.

    Search starts from specified index. By default, search starts from '0'.

      const myArray = [ 1, 2, 3, 4, 5 ]
      let myIndex = myArray.includes(4)
    
      console.log(myIndex); // true
    
  • findIndex(function(currentElement, index, array), thisValue)

    It executes a callback function for each array element and returns the index of first element which satisfies the condition given by callback function.

    It returns -1 if not element satisfies the condition.

      myArray = [ 1, 4, 3, 2, 5 ]
      let myIndex = myArray.findIndex( e => e % 2 == 0 )
    
      console.log(myIndex) // 1
    
  • find(function(currentElement, index, array), thisValue)

    It executes a callback function for each array element and returns the value of first element which satisfies the condition given by callback function.

    It return undefined if not element satisfies the condition.

      myArray = [ 1, 4, 3, 2, 5 ]
      let myIndex = myArray.findIndex( e => e % 2 == 0 )
    
      console.log(myIndex) // 4
    
  • some(function(currentElement, index, array), thisValue)

    It executes a callback function for each array element and returns true if any one of the array element satisfies the condition given by callback function otherwise it returns false.

      myArray = [ 1, 4, 3, 2, 5 ]
      let myIndex = myArray.some( e => e % 2 == 0 )
    
      console.log(myIndex) // true
    
  • every(function(currentElement, index, array), thisValue)

    It executes a callback function for each array element and returns true if all of the array element satisfies the condition given by callback function otherwise it returns false.

      myArray = [ 1, 3, 5, 7, 9 ]
      let myIndex = myArray.some( e => e % 2 != 0 )
    
      console.log(myIndex) // true
    

Sorting

  • sort(compareFunction)

    It sorts the array elements after converting them into string in ascending order.

    comapre function is used to sort a numeric array.

      myArray = [ 3,2,4,1,5 ]
      myArray.sort( (a,b) => a-b )
    
      console.log(myArray) // [ 1, 2, 3, 4, 5 ] sorted in ascending order
    
      myArray = [ 3,2,4,1,5 ]
      myArray.sort( (a,b) => b-a )
    
      console.log(myArray) // [ 5, 4, 3, 2, 1 ] sorted in descending order
    
      myArrayTwo = [ 'd', 'b', 'j', 'i', 'p' ]
      myArrayTwo.sort()
    
      console.log(myArrayTwo) // [ 'b', 'd', 'i', 'j', 'p' ]
    

Iteration

  • map(function(currentElement, index, array), thisValue)

    It executes a callback function for each array element.

    It returns the new array of modified elements.

      myArray = [ 1, 3, 5, 7, 9 ]
      let square = myArray.map( e => e**2 )
    
      console.log(square) // [ 1, 9, 25, 49, 81 ]
    
  • filter(function(currentElement, index, array), thisValue)

    It executes a callback function for each array element.

    It returns the new array of only elements that satisfies the condition provided by callback function.

      myArray = [ 1, 3, 5, 7, 9 ]
      let threes = myArray.filter( e => e % 3 == 0 )
    
      console.log(threes) // [ 3, 9 ]
    
  • reduce(function(accumulator, currentElement, index, array), initialValue)

    It executes a callback function for each array element.

    It reduces the array into a single value and returns that single value.

      myArray = [ 1, 3, 5, 7, 9 ]
      let sum = myArray.reduce( (  accumulator, e ) => accumulator + e , 0)
    
      console.log(sum) // 25
    
  • forEach(function(currentElement, index, array), thisValue)

    It executes a callback function for each array element.

    It may or may not modifies the original array.

    Return value is always undefined.

      const myArray = [1, 3, 5];
      const copy = [];
      myArray.forEach( e => copy.push(e*e) )
    
      console.log(copy) // [ 1, 9, 25 ]
    
  • entries()

    It returns the iterable object that contains the key/value pairs for each index in the array.

      const myArray = ['a', 'b', 'c']
    
      for (const [key, value] of myArray.entries()) {
      console.log(`${key}: ${value}`);
      } 
    
      /*
      output -
    
      0: a
      1: b
      2: c    
    
      */
    

Some more useful methods

  • concat(arr1, arr2, arrN) : It concats two or more arrays and returns a new array.

      const myArray = ['a', 'b', 'c']
      const myArrayTwo = ['d', 'e', 'f']
      const myArrayThree = myArray.concat(myArrayTwo)
    
      console.log(myArrayThree) // [ 'a', 'b', 'c', 'd', 'e', 'f' ]
    
  • join(separator) : It converts an array into a string separated by a specified separator. It returns a new string. Default separator is ,.

      const myArray = ['a', 'b', 'c']
      let myString = myArray.join('')
    
      console.log(myString)  // 'abc'
    
  • reverse() : It reverses the order of an array. It overwrites the original array.

      const myArray = ['a', 'b', 'c']
    
      console.log(myArray.reverse())  // [ 'c', 'b', 'a' ]
    
  • slice(start, end) : It returns selected elements as a new array.

      const myArray = ['a', 'b', 'c', 'd', 'e']
      const slicedArray = myArray.slice(1,4)
    
      console.log(slicedArray)  // [ 'b', 'c', 'd' ]
    

Final Words

And that’s basically it for this blog.

I hope you’ve found this blog a good referencing resource and thank you for reading.

If this blog was helpful, please do like, comment and share. Thanks, see you in the next article.✌️