JavaScript array methods explained

jainpranayr

Pranay Jain

Posted on February 11, 2022

JavaScript array methods explained

An array is a collection of values in JavaScript. It comes with several built-in properties and methods that we can use to add, remove, iterate, and manipulate data as needed. Knowing JavaScript array methods can also help you improve your programming skills.

In this article, we'll look at all the array methods in JavaScript that will assist you in effectively manipulating your data.

Let's get started.

  • push()

The push() appends one or more elements to the end of an array.Here’s the syntax of the push() method:

Array.push(element)
Enter fullscreen mode Exit fullscreen mode

Some examples:

// add single element
let nums = [10,20,30,40]
nums.push(50) // nums = [10,20,30,40,50]

// add multiple elements
let nums = [10,20,30]
nums.push(40, 50) // nums = [10,20,30,40,50]

// add elements of an array to another array
let peoples = ["john","jane","steve"]
let nums = [1,2,3.4]
peoples.push(...nums) // peoples = ['john', 'jane', 'steve', 1, 2, 3.4]
Enter fullscreen mode Exit fullscreen mode
  • unshift()

The unshift() method adds one or more elements to the beginning of an array.Here’s the syntax of the push() method:

Array.unshift(element)
Enter fullscreen mode Exit fullscreen mode

Some examples:

// add single element
let nums = [10,20,30,40]
nums.unshift(50) // nums = [50,10,20,30,40]

// add multiple elements
let nums = [10,20,30]
nums.unshift(40, 50) // nums = [40,50,10,20,30]
Enter fullscreen mode Exit fullscreen mode
  • pop()

The pop() method deletes the last element from an array. The pop() method has the following syntax:

The pop() method changes the length property of the array. If the array is empty, the pop() returns undefined.

Array.pop()
Enter fullscreen mode Exit fullscreen mode

Some examples:

const nums = [10,20,30]
nums.pop() // nums = [10,20]

// using pop() with an empty array
const names = []
names.pop() // names = undefined
Enter fullscreen mode Exit fullscreen mode
  • shift()

The shift() method deletes the first element from an array. The shift() method has the following syntax:

Array.shift()
Enter fullscreen mode Exit fullscreen mode

Some examples:

const nums = [10,20,30]
nums.shift() // nums = [10,20]
Enter fullscreen mode Exit fullscreen mode
  • splice()

The splice() method is used to delete existing elements, insert new elements, and replace elements in an array.

Deleting elements using splice() method.

To delete elements, you pass two arguments in splice() as follows:

Array.splice(position,num)
Enter fullscreen mode Exit fullscreen mode

The position argument provides the first item to delete, while the num argument specifies the number of elements to delete.

let scores = [10,20,30,40]
scores.splice(0,2) // scores = [10,20]
Enter fullscreen mode Exit fullscreen mode

Inserting elements using splice() method.

You can insert one or more elements into an array by passing three or more arguments to the splice() method, with the second argument set to 0 as follows:

Array.splice(position,0,new_element1,new_element2)
Enter fullscreen mode Exit fullscreen mode

The position argument specifies the starting position in the array that the new elements will be inserted.

The second argument (0) instructs the splice() method to not delete any array elements.

The third argument, fourth argument, and so on are the new elements that are inserted into the array.

example:

let colors = ['red', 'green', 'blue']
colors.splice(2, 0, 'purple') // colors = ["red", "green", "purple", "blue"]
Enter fullscreen mode Exit fullscreen mode

Replacing elements using splice() method.

To replace elements in an array, you must pass at least three arguments. The first argument specifies the starting position to insert, second one specifies numbers of elements to insert and the third argument specifies the element to insert.

example:

let languages = ['C', 'C++', 'Java', 'JavaScript']
languages.splice(1, 1, 'Python') // replaces C++ with python
Enter fullscreen mode Exit fullscreen mode
  • slice()

The slice() method allows you to clone an array or copy a section of an array into a new array. The slice() method accepts two optional arguments as follows:

Array.slice(start,stop)
Enter fullscreen mode Exit fullscreen mode

The start argument specifies the index from which to begin extraction. slice() starts at 0 if the start parameter is undefined.

The stop argument specifies a index at which extraction should be terminated. The slice() method extracts up to stop-1. If you don't specify a stop parameter, the slice() method will take the array's length as the stop parameter.

examples:

// clone an array
const nums = [1,2,3,4,5]
const newNums = nums.slice() // newNums = [1,2,3,4,5]

// copy a portion of an array
const colors = ['red','green','blue','purple','yellow']
const rgb = colors.slice(0,3) // rgb= ['red','green','blue']
Enter fullscreen mode Exit fullscreen mode
  • some()

some() is used to see if at least one element in an array passes a test.The test condition is implemented by passing a callback function to the some() method.

const marks = [4,5,6,7,9,10,3]
const lessThanFiveExists = marks.some(function(m) {
    return m < 5
} // true

// shorter syntax
const lessThanFiveExists = marks.some(m => m < 5)
Enter fullscreen mode Exit fullscreen mode

If you call the some() method on an empty array, the result is always false regardless of any condition. For example:

let names = []
names.some(n => n > 0) // false
Enter fullscreen mode Exit fullscreen mode
  • every()

The every() method is used to test all of the elements in an array. Like the some() method, every() uses the callback method to test elements.

const nums = [1,2,4,5]
const isEven = nums.every(function (e) {
    return e % 2 === 0;
}) // false

// shorter syntax
const isEven = nums.every(n => n % 2 === 0)
Enter fullscreen mode Exit fullscreen mode

If you call the every() method on an empty array, the result is always true for any condition. For example:

const nums = []
const ltZero = nums.every(n => n < 0) // true
Enter fullscreen mode Exit fullscreen mode
  • sort()

The sort() method is used to sort arrays of numbers, strings, and objects.

The sort() method, by default, sorts the array elements in ascending order, with the smallest value first and the greatest value last.

The sort() method converts elements to strings and compares them to determine the order.

Consider the following example:

const nums = [0,1,2,3,10,20,30]
nums.sort() // [0,1,10,2,30,3,30]
Enter fullscreen mode Exit fullscreen mode

In this example, the sort() method puts 10 before 2 because the string "10" occurs before "2" when doing a string comparison.

To fix this, you need to pass a compare function as an argument to sort() method. The compare function will be used by the sort() method to determine the order of elements.

const nums = [0, 1 , 2, 3, 10, 20, 30 ]
nums.sort( function( a , b){
    if(a > b) return 1
    if(a < b) return -1
    return 0
}) // [ 0,  1,  2, 3, 10, 20, 30 ]

// using arrow function
nums.sort((a,b) => {
    if(a > b) return 1
    if(a < b) return -1
    return 0;
})

// simplest version
numbers.sort((a, b) => a - b)
Enter fullscreen mode Exit fullscreen mode
  • map()

The map() method is used to transform elements in an array. The map() method calls a callback function on every element of an array and returns a new array that contains the results.

const nums = [16,25,36]
nums.map(num => num * num) // [4,5,6]
Enter fullscreen mode Exit fullscreen mode
  • filter()

The filter() method is used to filter out elements in an array. The filter() method iterates over every element in array and passes each element to a callback function. If the callback function returns true, it returns the element in the array.

const cities = [
    {name: 'Delhi', population: 3792621},
    {name: 'Jaipur', population: 8175133},
    {name: 'Nashik', population: 2695598},
    {name: 'Srinagar', population: 2099451},
    {name: 'Mysore', population: 1526006}
]

const bigCities = cities.filter(city => city.population > 3000000) // [{name: 'Delhi', population: 3792621}, {name: 'Jaipur', population: 8175133}]
Enter fullscreen mode Exit fullscreen mode
  • forEach()

The forEach() method is used to exeucte a function on every element in an array. The forEach() method iterates over elements in an array and executes a callback function on every element.

const nums = [1,2,3]
let sum = 0
nums.forEach(num => sum += num)
// sum = 6
Enter fullscreen mode Exit fullscreen mode
  • reduce()

The reduce() method receives a callback function which has an accumulator and a value as an argument. It uses the callback function on the accumulator as well as each value in the array to return a single value in the end. For example:

const nums = [1,2,3,4,5]
nums.reduce((products,value) => products * value)
// OUTPUT: 1*2*3*4*5 = 120
Enter fullscreen mode Exit fullscreen mode
  • join()

The join() method concatenates elements in an array and returns a string. The syntax for join() method is as follows:

Array.join(separator)
Enter fullscreen mode Exit fullscreen mode

The join() method accepts separator as an optional argument, which is a string that separates neighboring array elements.
If you don't give a separator to the join() method, it defaults to a comma.
When the array's elements aren't strings, the join() method turns them into string before joining them.
Note that the join() method turns undefined, null, and [] to an empty string.

const cssClasses = ['btn','btn-primary','btn-active']
const btnClass = cssClasses.join(' ') // btn btn-primary btn-active
Enter fullscreen mode Exit fullscreen mode
  • flat()

The flat() method recursively concatenates all the items of the subarrays to a new array up to a specified depth. The syntax for the flat() method is as follows:

let newArray = Array.flat(depth)
Enter fullscreen mode Exit fullscreen mode

The depth parameter defines how deep the array is flattened by the method. It is set to 1 by default.

const nums = [1, 2, [3, 4, 5, [6, 7]]]
const flatNums = nums.flat(2) // [1, 2, 3, 4, 5, 6, 7]
Enter fullscreen mode Exit fullscreen mode
  • flatMap()

The flatMap() method uses a mapping function to map each element in an array and flattens the result into a new array. The flatMap() method is the combination of the map() method followed by the flat() method of depth 1.

const nums = [[1], [2], [3], [4], [5]]
const doubled = nums.flatMap(num => num * 2) // [2,4,6,8,10]

// using flat() and map() method
const doubled = nums.flat().map(num => num * 2)
Enter fullscreen mode Exit fullscreen mode
  • indexOf()

The indexOf() and lastIndexOf() methods are used to find the position of an element in an array.This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.

The syntax for the method is as follows:

Array.indexOf(searchElement) 
Array.lastIndexOf(searchElement)
Enter fullscreen mode Exit fullscreen mode

The indexOf() and lastIndexOf() methods searchElement as an argument.
indexOf() and lastindexOf() methods use triple-equals operator (===) when comparing the searchElement with elements in the Array.

examples of indexOf() method:

const nums = [10,20,30,40,30]
nums.indexOf(30) // 2
nums.indexOf(60) // -1
Enter fullscreen mode Exit fullscreen mode

examples of lastIndexOf() method:

const nums = [10,20,30,40,30]
nums.lastIndexOf(40) // 1
nums.lastIndexOf(30) // 0
Enter fullscreen mode Exit fullscreen mode

nums.lastIndexOf(30) method returns 0 while nums.indexOf(30) method returns 2.
that is because, indexOf() method searches for element forward and lastIndexOf() method searches element backward.

  • at()

The at() method accepts an index and returns an element at that index.

For a positive index, the method returns the element at that index.

For a negative index, the method returns an element from the end of the array. For example, the arr.at(-1) returns the last element, arr.at(-2) returns the second last element, and so on.

const nums = [30,40,50,60]
nums.at(1) // 40
nums.at(-3) // 40
Enter fullscreen mode Exit fullscreen mode
  • of()

This method assists us in improving array formation.

const myArray = Array.of(1,2,'A','C',true,false) // myArray = [1, 2, 'A', 'C', true, false]
Enter fullscreen mode Exit fullscreen mode
  • find()

The find() method is used to search for the first element in an array, which satisfies a test. The test condition is supplied as a callback function.

const nums = [1,2,3,4,5]
const evenNums = nums.find(num => num % 2 === 0) // 2
Enter fullscreen mode Exit fullscreen mode
  • findIndex()

The findIndex() method is used to find the first element that satisfies a given test.

const nums = [1,2,3,4,5]
nums.findIndex(num => num % 2 === 0) // 1
Enter fullscreen mode Exit fullscreen mode
  • includes()

The includes() method checks if an element is in an array.

const nums = [1,2,3]
nums.includes(2) // true
Enter fullscreen mode Exit fullscreen mode
  • concat()

The concat() method is used to merge two or more arrays into a single array.

const odds = [1,3,5]
const evens = [2,4,6]

const nums = odds.concat(evens) // nums = [1,3,5,2,4,6]
Enter fullscreen mode Exit fullscreen mode

Thank you for taking the time to read!!

💖 💪 🙅 🚩
jainpranayr
Pranay Jain

Posted on February 11, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related