12 Javascript Array Methods Explained

12 Javascript Array Methods Explained

What is JavaScript Array?

Arrays are special type of object in JavaScript, array is a single variable used in storing different items.

It is often used when we want to store collection of any data type and access them by a single variable. This means that you can create an array with items of type String, Boolean, Number, Objects, and even other Arrays.

An array is stored in a pair of square brackets [] in JavaScript and the items in the array are separated by a comma (,).

Below is an example of an array with three different items data type, i.e. String, Number, Boolean, and Object.

const diffDataTypeArray = ['Hashnode', 145,  true];

The position of an item in the array is known as index. In JavaScript, the array index starts with 0.

In the array example above, the item Hashnode is indexed at 0, 145 is indexed at 1, while true is indexed at 2.

The number of items in the array determines its length. For example, the length of the above array is four.

Interestingly, arrays, have different inbuilt functions or methods which are quite helpful to developers. In this article, we are going to discuss 16 array methods and what they do. Let’s ride!!!

List of JavaScript Array Methods

There are other array methods, however, we are going to discuss few of them. Below are the 13 popular JavaScript arrays and we going to briefly explain each one of them with an example.

  1. push()
  2. pop()
  3. shift()
  4. unshift()
  5. slice()
  6. splice()
  7. concat()
  8. includes()
  9. filter()
  10. findIndex()
  11. map()
  12. sort()

push()

The push() method is used to add new items to the end an array. For example;

const cars = [‘Honda’, ‘Mercedes Benz’, ‘BMW’, ‘Toyota’]
cars.push(‘Lexus’)
// outputs [‘Honda’, ‘Mercedes Benz’, ‘BMW’, ‘Toyota’, ‘Lexus’]

pop()

pop() removes and returns the last item in an array.

const cars = [‘Honda’, ‘Mercedes Benz’, ‘BMW’, ‘Toyota’]
cars.pop()
// returns ‘Toyota’

shift()

shift() method removes and returns first item of an array.

const cars = [‘Honda’, ‘Mercedes Benz’, ‘BMW’, ‘Toyota’]
cars.shift() 
// returns ‘Honda’

unshift()

Unlike push(), unshift() adds new items to the beginning of an array.

const cars = [‘Honda’, ‘Mercedes Benz’, ‘BMW’, ‘Toyota’]
cars.unshift(‘Audi’)
// returns [‘Audi, ‘Honda’, ‘Mercedes Benz’, ‘BMW’, ‘Toyota’, ‘Lexus’]

slice()

The slice() method is used to select elements in an array. The syntax looks like this; arr.slice([start], [end]).

const cars = ["Audi", "Mercedes Benz", "BMW", "Toyota", "Lexus"]
cars.slice(2, 4) // returns ["Mercedes Benz", ‘BMW"]

slice() can select elements backwards by adding a minus sign to the number.

const cars = ["Audi", "Mercedes Benz", "BMW", "Toyota", "Lexus"]
cars.slice(-2) // returns last two elements ["Toyota", "Lexus"]

slice() returns a copy of array when called with no arguments. e.g. cars.slice()

splice()

This method is versatile amongst JavaScript array methods. splice() can remove or add items to the array. The syntax array.splice(index, count, item1, ....., itemX)

Removing elements with splice()

const cars = ["Audi", "Mercedes Benz", "BMW", "Toyota", "Lexus"]
cars.splice(3, 2) // removes the last two items ["Toyota", "Lexus"]
// meaning; from index 3, remove 2 elements

Adding elements with splice()

const cars = ["Audi", "Mercedes Benz", "BMW"]
cars.splice(1, 0, "Honda", "Ford") 
// meaning; from index 1, remove nothing, but add "Honda", "Ford"
// now -> ["Audi", "Honda", "Ford", "Mercedes Benz", "BMW"]

concat()

concat() simply joins different arrays and returns a new one with existing arrays unchanged.

const germanCars = ["Audi", "Mercedes Benz", "BMW"]
const japaneseCars = ["Toyota", "Nissan"] 

const cars = germanCars.concat(japaneseCars)
// cars now -> ["Audi", "Mercedes Benz", "BMW", "Toyota", "Nissan"]

includes()

includes() is one of the search array methods, includes() returns a Boolean.

const cars = ["Audi", "Mercedes Benz", "BMW", "Toyota", "Nissan"]

cars.includes("Nissan") // returns true
cars.includes("Ford") // returns false

filter()

filter() returns an array of all matching elements. For example.

const cars = [ {id: 1, brand: "Audi", year: 2022},
                        {id: 2, brand: "Mercedes Benz", year: 2015},
                        {id: 3, brand: "BMW", year: 2021}, 
                        {id: 4, brand: "Nissan", year: 2011}
                      ];
const selectedCars = cars.filter(item => item.year > 2020)
// iterate through cars array 
// filters cars that their year of make are beyond 2020
// pushes filtered elements to selectedCar
// selectedCar displays [ {id: 1, brand: "Audi", year: 2022}, 
// {id: 2, brand: "BMW", year: 2021}
// ];

findIndex()

The findIndex() syntax is similar to filter() method, it returns the index of the matching element instead of the element itself. findIndex() returns -1 if no match is found.

const cars = [ {id: 1, brand: "Audi", year: 2022},
                        {id: 2, brand: "Mercedes Benz", year: 2015},
                        {id: 3, brand: "BMW", year: 2021}, 
                        {id: 4, brand: "Nissan", year: 2011}
                      ];
const selectedCars = cars.findIndex(item => item.brand === "BMW")
// returns 2

map()

This method is one of the most used array method. The map() method creates an array by calling a specific function on each element present in the parent array.

const arrNum = [100, 150, 200, 1000]
arrNum.map(item => item * 2) // displays [200, 300, 400, 2000]

sort()

As the name implies, sort() simply sorts arrays alphabetically or numerically as the case may be.

const cars = ["Audi", "Mercedes Benz", "BMW", "Toyota", "Nissan"]
cars.sort()
// outputs ['Audi', 'BMW', 'Mercedes Benz', 'Nissan', 'Toyota']

const scores = [3, , 200, 5, 9, 4, 6, 1, 7, 100]
scores.sort(( (a, b) => a - b ))
// outputs  [1, 3, 4, 5, 6, 7, 9]

Wrapping up

There are other JavaScript methods, however, these are the few popular ones handpicked for topic of discussion in this article.

Thanks for reading - and if you have any questions/suggestions, kindly leave them in the comments section below, and I'll be glad to answer every single one.