Top 10 Handy JavaScript Array Methods You Should Know5 min read

An array in JavaScript is a data structure that helps you store multiple values at a time. Indeed when working with JavaScript you need to work with arrays quite often, then knowing some crucial array methods is enormously important to increase your productivity and lift up your skills as a JavaScript developer.

In this article, we are going to examine the top 10 handy array methods that you should know. But before we start, make sure you already familiar with these concepts:

1. map()

The map() method accepts a callback function as the first parameter and creates a new array as an image of the provided callback function in every element in the calling array. The callback function is called for every element of the array, each time the callback function executes, the result is added to the new array with the same amount of elements.

const array = [1, 2, 3, 4];
const array2 = array.map(x => x * 2);
console.log(array2); // [ 2, 4, 6, 8 ]

const array3 = array.map(x => x * x);
console.log(array3); // [ 1, 4, 9, 16 ]

2. filter()

The filter() method creates a new array with elements that pass the test implemented by the provided callback function.

const array = [5, 6, 7, 8, 9, 10];
const filteredArray = array.filter(number => number > 7);
console.log(filteredArray); // [ 8, 9, 10 ]

const anotherArray = [49, 21, 83, 62, 51, 54, 69];
const multiplesOfSeven = anotherArray.filter(number => number % 7 == 0);
console.log(multiplesOfSeven); // [ 49, 21 ]

3. sort()

The sort() method is a built-in JavaScript method that allows you to sort elements of the array in place and returns the sorted array. The default sorting order is ascending, it first converts elements into strings, then comparing their sequences of UTF-16 code values.

const letters = ["X", "Z", "A", "C", "D", "F", "J", "N", "H"];
letters.sort();
console.log(letters); // [ 'A', 'C', 'D', 'F', 'H', 'J', 'N', 'X', 'Z' ]

If we want to sort elements of numbers in ascending order, we need to provide the sort() method a conditioning callback function otherwise by default it will convert elements into strings and then compares their UTF-16 code values:

const numbers = [6000, 2000, 1000000, 20, 1999];
numbers.sort();
console.log(numbers); // [ 1000000, 1999, 20, 2000, 6000 ]

We can sort elements in ascending order like this:

const numbers = [6000, 2000, 1000000, 20, 1999];
function compare(a, b) {
    if (a < b) {
        return -1;
    } else if (a == b) {
        return 0;
    } else {
        return 1;
    }
}
numbers.sort(compare);
console.log(numbers); // [ 20, 1999, 2000, 6000, 1000000 ]

Or simply like this:

const numbers = [6000, 2000, 1000000, 20, 1999];
numbers.sort((a, b) => a - b);
console.log(numbers); // [ 20, 1999, 2000, 6000, 1000000 ]

Sorting elements in descending order:

const numbers = [6000, 2000, 1000000, 20, 1999];
numbers.sort((a, b) => b - a);
console.log(numbers) // [ 1000000, 6000, 2000, 1999, 20 ]

4. reduce()

This method takes a function which has an accumulator and a value as an argument and the reduce() method applies this function to every element of the array from left to right, resulting in a single output value.

const a = [1, 2, 3, 4, 5];
const b = a.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(b); // 1 + 2 + 3 + 4 + 5 = 15

You also can provide an optional initial value passed to the function:

const numbers = [1, 2, 3, 4, 5];
const reducedNumber = numbers.reduce((accumulator, currentValue) => accumulator * currentValue, 5);
console.log(reducedNumber); // 5 * 1 * 2 * 3 * 4 * 5 = 600

5. forEach()

The forEach() method calls a function once for each element in an array, in order and it always returns undefined value at the end.

const languages = ["JS", "Python", "Java", "Haskell"];
const array = [];
languages.forEach(x => array.push(x + " is awesome!"));
console.log(array); 
/* 
 [ 'JS is awesome!',
  'Python is awesome!',
  'Java is awesome!',
  'Haskell is awesome!' ] 
*/

const people = [
    { name: "Nam", age: 69 },
    { name: "Justin", age: 23 },
    { name: "Austin", age: 28 }
]
people.forEach(person => console.log(person.name)); 
/*
Nam
Justin
Austin
*/

6. reverse()

This method reverses the order of the array in-place, the first element will become the last, and vice versa.

const numbers = [10, 20, 30, 40, 50];
const reversed = numbers.reverse();
console.log(reversed); // [ 50, 40, 30, 20, 10 ]

const letters = ["A", "B", "C", "D", "E"];
const reversedOrder = letters.reverse();
console.log(reversedOrder); // [ 'E', 'D', 'C', 'B', 'A' ]

7. indexOf()

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

const names = ["Nam", "Justin", "Juan", "Christopher", "Michael", "Nam"];
console.log("Index of 'Nam' is " + names.indexOf('Nam'));

You also can specify the second parameter which is the start index, where the method begins to find the index’s element, for example, we want to find the index of the element 'Nam' from the second index till the end:

const names = ["Nam", "Justin", "Juan", "Christopher", "Michael", "Nam"];
console.log("Index of 'Nam' is " + names.indexOf('Nam', 1)); // Index of 'Nam' is 5

This method will return -1 in case it cannot find the index of the element that you are looking for:

const nums = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(nums.indexOf(9)); // -1

8. concat()

The concat() method is used to merge two or more arrays. But it doesn’t change the existing arrays, instead, it returns a new array after merging.

const arr1 = ["Where", "the", "north", "wind"];
const arr2 = ["meets", "the", "sea"];
const arr3 = arr1.concat(arr2);
console.log(arr3); // [ 'Where', 'the', 'north', 'wind', 'meets', 'the', 'sea' ]

const nums = [1, 2, 3];
const letters = ['a', 'b', 'c'];
console.log(nums.concat(letters)); // [ 1, 2, 3, 'a', 'b', 'c' ]
console.log(nums); // [ 1, 2, 3 ]
console.log(letters); // [ 'a', 'b', 'c' ]

9. join()

The join() method creates and returns a new string which is the concatenation of all elements in the array it applies, it accepts one parameter as a separator to separate elements in this array.

const a = ["Where", "the", "north", "wind", "meets", "the", "sea"];
// use "" as the separator for array elements
console.log(a.join("")); // Wherethenorthwindmeetsthesea
// use " " as the separator for array elements
console.log(a.join(" ")); // Where the north wind meets the sea
// use "-" as the separator for array elements
console.log(a.join("-")); // Where-the-north-wind-meets-the-sea

If the array has only one item, then that item will be returned without using the separator.

const x = ["Something"];
console.log(x.join()); // Something

10. includes()

The includes() method returns true if the array contains a certain element, false if not.

const arr1 = [1, 2, 3, 4, 5];
console.log(arr1.includes(1)); // true

const arr2 = ['one', 'two', 'four'];
console.log(arr2.includes('three')); // false

This method accepts the second parameter, which is the position in this array at which to begin searching for the value we want to find.

const arr3 = [1, 2, 3];
// find value 1 in the arr3 starting from index 2
console.log(arr3.includes(1, 2)); // false

Facebook Comments

Previous Article
Next Article

Sign up for newsletter

* indicates required

Categories

Archives