login

JavaScript array methods every developer must know

9 August 2020

In this post, you will learn helpful methods in JavaScript Array. An array is one of the most common data structures that we use a lot. I will be going over array methods that are going to use a lot as a programmer. These array methods will make your life easier in your javascript project. Here is the list of all array methods provided by the Array class. Today we are going to discuss the following important 15 array methods

  • map()
  • filter()
  • reduce()
  • reduceRight()
  • every()
  • some()
  • includes()
  • concat()
  • sort()
  • slice()
  • splice()
  • pop()
  • shift()
  • push()
  • unshift()

1: map()

The map() method creates a new array containing the results of calling a provided function on every element in the calling array

The callback function runs once for each element in an array, in order, and constructs a new array from the results. It is invoked only for indexes of the array which have assigned values (including undefined). Please note that it is not called for missing elements of the array

map() is invoked with a callback function with the following three arguments:

  • currentValue - The current element being processed in the array
  • indexOptional (Optional) - The index of the current element being processed in the array
  • array (Optional) - The array, map method was called upon
const heros =
[{ id: 1,  name: "Iron Man",   fullName: "Tony Stark",     publisher: "Marvel Comics" },
 { id: 2,  name: "Batman",     fullName: "Terry McGinnis", publisher: "DC Comics"     },
 { id: 3,  name: "Spider-Man", fullName: "Peter Parker",   publisher: "Marvel Comics" },
 { id: 4,  name: "Venom",      fullName: "Eddie Brock",    publisher: "Anti-Venom"    },
 { id: 5,  name: "Deadpool",   fullName: "Wade Wilson",    publisher: "Evil Deadpool" },
 { id: 6,  name: "Thanos",     fullName: "Tony Stark",     publisher: "Marvel Comics" },
 { id: 7,  name: "Thor",       fullName: "Thor Odinson",   publisher: "Marvel Comics" },
 { id: 8,  name: "Hulk",       fullName: "Bruce Banner",   publisher: "Marvel Comics" },
 { id: 9,  name: "Flash",      fullName: "Jay Garrick",    publisher: "DC Comics"     },
 { id: 10, name: "Wolverine",  fullName: "Logan",          publisher: "Marvel Comics" }];

const transformedHeros = heros.map((element) => {
    return {
        name: element.name,
        publisher: element.publisher,
        isFamous: true,
    }
});
console.log(transformedHeros);
// OUTPUT //
[{ name: 'Iron Man', publisher: 'Marvel Comics', isFamous: true },
 { name: 'Batman', publisher: 'DC Comics', isFamous: true },
 { name: 'Spider-Man', publisher: 'Marvel Comics', isFamous: true },
 { name: 'Venom', publisher: 'Anti-Venom', isFamous: true },
 { name: 'Deadpool', publisher: 'Evil Deadpool', isFamous: true },
 { name: 'Thanos', publisher: 'Marvel Comics', isFamous: true },
 { name: 'Thor', publisher: 'Marvel Comics', isFamous: true },
 { name: 'Hulk', publisher: 'Marvel Comics', isFamous: true },
 { name: 'Flash', publisher: 'DC Comics', isFamous: true },
 { name: 'Wolverine', publisher: 'Marvel Comics', isFamous: true }]

When you need to transform input array into a new array use map() method

2: filter()

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

filter() is invoked with a callback function with the following three arguments:

  • currentValue - The current element being processed in the array
  • indexOptional (Optional) - The index of the current element being processed in the array
  • array (Optional) - The array, filter method was called upon
const heros =
 [{ id: 1,  name: "Iron Man",   fullName: "Tony Stark",     publisher: "Marvel Comics" },
  { id: 2,  name: "Batman",     fullName: "Terry McGinnis", publisher: "DC Comics"     },
  { id: 3,  name: "Spider-Man", fullName: "Peter Parker",   publisher: "Marvel Comics" },
  { id: 4,  name: "Venom",      fullName: "Eddie Brock",    publisher: "Anti-Venom"    },
  { id: 5,  name: "Deadpool",   fullName: "Wade Wilson",    publisher: "Evil Deadpool" },
  { id: 6,  name: "Thanos",     fullName: "Tony Stark",     publisher: "Marvel Comics" },
  { id: 7,  name: "Thor",       fullName: "Thor Odinson",   publisher: "Marvel Comics" },
  { id: 8,  name: "Hulk",       fullName: "Bruce Banner",   publisher: "Marvel Comics" },
  { id: 9,  name: "Flash",      fullName: "Jay Garrick",    publisher: "DC Comics"     },
  { id: 10, name: "Wolverine",  fullName: "Logan",          publisher: "Marvel Comics" }];

 // GET HEROS PUBLISHED BY MARVEL COMICS
 const transformedHeros = heros.filter((element) => {return  element.publisher === 'Marvel Comics'});
 console.log(transformedHeros);
 // OUTPUT //
[{ id: 1,  name: "Iron Man",   fullName: "Tony Stark",     publisher: "Marvel Comics" },
{ id: 3,  name: "Spider-Man", fullName: "Peter Parker",   publisher: "Marvel Comics" },
{ id: 6,  name: "Thanos",     fullName: "Tony Stark",     publisher: "Marvel Comics" },
{ id: 7,  name: "Thor",       fullName: "Thor Odinson",   publisher: "Marvel Comics" },
{ id: 8,  name: "Hulk",       fullName: "Bruce Banner",   publisher: "Marvel Comics" },
{ id: 10, name: "Wolverine",  fullName: "Logan",          publisher: "Marvel Comics" }]

When you need to filter input array into a new array use filter() method

3: reduce()

The reduce() method executes a reducer function on each element of the array (from left to right), resulting in a single output value

This can be difficult to understand especially with all the vague explanations that can be found on the web

The reducer function takes four arguments:

  • accumulator - The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback
  • currentValue - The current element being processed in the array
  • indexOptional (Optional) - The index of the current element being processed in the array
  • array (Optional) - The array, reduce method was called upon
const numbers = [10, 7, 5];
// Sum of all array elements
const sum = numbers.reduce(
    (accumulator, currentValue) => {
        console.log('accumulator:', accumulator)
        return accumulator + currentValue;
    },
    0
)
console.log('sum:', sum)
// OUTPUT //
accumulator: 0
accumulator: 10
accumulator: 17
22

Let's break down what happens in the reduce method using the above example. We have passed the reducer function and initial value of the accumulator as an argument. Let's see what happened when we looped over the numbers array

  • In first iteration, The initial value of accumulator as 0(second argument of reduce method). 'accumulator: 0' got logged. In second line of reducer function currentValue(10) got added in accumulator(accumulator = 0 + 10)
  • In second iteration, The accumulator now has value 10 so 'accumulator: 10' got logged. In second line of reducer function currentValue(7) got added in accumulator(accumulator = 10 + 7)
  • In third iteration, The accumulator now has value 17 so 'accumulator: 17' got logged. In second line of reducer function currentValue(5) got added in accumulator(accumulator = 17 + 5)
  • After array iteration is complete, reduce function returned the accumulator(22) and stored in sum variable and 'sum: 22' got logged

Please note the following mistakes while using reduce method

  • If you don’t pass in an initial value, reduce will assume the first item in your array is your initial value
  • You must return something for the reduce function to work. Always double-check and make sure that you’re returning the value you want

When to use => when you want to map and filter together and you have a lot of data to go over use reduce() method

4: reduceRight()

The reduceRight() method executes a reducer function on each element of the array (from right to left), resulting in a single output value

In short, reduceRight() works the same as the reduce(), the only difference is in order of processing array elements

The reducer function takes four arguments, the same as reduce() method:

  • accumulator - The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback
  • currentValue - The current element being processed in the array
  • indexOptional (Optional) - The index of the current element being processed in the array
  • array (Optional) - The array, reduceRight method was called upon
const numbers = [10, 7, 5];

// Sum of all array elements
const sum = numbers.reduceRight(
    (accumulator, currentValue) => {
        console.log('accumulator:', accumulator)
        return accumulator + currentValue;
    },
    0
)
console.log('sum:', sum)

// OUTPUT //
accumulator: 0
accumulator: 5
accumulator: 12
sum: 22

I'm not going over how this code worked as it works the same as reduce() method

When to use => When you need to reduce an array from Right to left use the reduceRight() method

5: every()

every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a boolean value

every() is invoked with a callback function with the following three arguments:

  • currentValue - The current element being processed in the array
  • indexOptional (Optional) - The index of the current element being processed in the array
  • array (Optional) - The array, every method was called upon
const numbers1 = [10, 0, -5, 8, 9];
// Check if every number in array is positive
console.log(numbers1.every((e) => e > 0))
// false

const numbers2 = [35, 50, 52, 48, 39];
// Check if every number in array is greater than 30
console.log(numbers2.every((e) => e > 30))
// true

When to use => When you need to check if every array element/object satisfies a particular condition, use every() method

6: some()

The some() method tests whether at least one of the elements in the array passes the test implemented by the provided function. It returns a boolean value

some() is invoked with a callback function with the following three arguments:

  • currentValue - The current element being processed in the array
  • indexOptional (Optional) - The index of the current element being processed in the array
  • array (Optional) - The array, some method was called upon
const numbers1 = [10, 0, -5, 8, 9];
// Check if some numbers in the array are negative
console.log(numbers1.some((e) => e < 0))
// true

const numbers2 = [35, 50, 52, 48, 39];
// Check if some numbers in the array are greater than 100
console.log(numbers2.some((e) => e > 100))
// false

When to use => When you need to check if at least one array element/object satisfies a particular condition, use some() method

7: includes()

The includes() method case-sensitively determines whether an array contains a specified element. It returns true if the array contains the element otherwise false.

includes() can be invoked with the following two arguments:

  • element - The element to search for
  • startIndex (Optional) - Default 0. At which position in the array to start the search
const fruits = ["Banana", "Peach", "Apple", "Mango", "Orange"];

console.log(fruits.includes("Mango"));
// true
console.log(fruits.includes("Jackfruit"));
// false

When to use => When you need to find if a value exists in an array

8: concat()

The concat() method is used to merge two or more arrays. It returns a new array containing all the elements of calling and called arrays

concat() can be invoked with the following argument:

  • nArray (Optional) - one or more Arrays and/or values to concatenate
const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];
console.log(num1.concat(num2, num3));
// [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(num1.concat(num3));
// [1, 2, 3, 7, 8, 9]

When to use => When you need to merge two or more arrays without modifying existing arrays

9: sort()

The sort() method sorts array elements. By default, alphabetically sorts the elements. If you want numerically sort the elements we can do it with the help of the comparator function

const fruits = [ "Banana", "Peach", "Apple", "Mango", "Orange" ];

console.log(fruits.sort());
// [ 'Apple', 'Banana', 'Mango', 'Orange', 'Peach' ]

const numbers = [100, 1, 40, 5, 25, 10];
console.log(numbers.sort());
// [ 1, 10, 100, 25, 40, 5 ]

console.log(numbers.sort((a, b) => { return a - b }));
// [ 1, 5, 10, 25, 40, 100 ]

Let's see what happened in above examples

  • The first example is pretty straightforward. fruits array got sorted alphabetically
  • In the second example, [1, 10, 100, 25, 40, 5] got printed. That's weird. It happened because the array got sorted alphabetically not numerically. eg: "25" is bigger than "100", because "2" is bigger than "1"
  • In the third example, We corrected the above example with the help of the comparator function

When to use => When you need to sort elements of an array

10: slice()

The slice() method returns the selected elements in a new array

slice() is invoked with the following 2 arguments:

  • startIndex (Optional) - An integer that specifies where to start the selection. You can use negative numbers to select from the end of an array. If ignored, it acts like "0"
  • endIndex (Optional) - An integer that specifies where to end the selection. If ignored, all elements from the start position and to the end of the array will be selected. You can use negative numbers to select from the end of an array
const fruits = ["Banana", "Peach", "Apple", "Mango", "Orange"];
console.log(fruits.slice(2, 4));
// [ 'Apple', 'Mango' ]
console.log(fruits.slice(3));
// [ 'Mango', 'Orange' ]

When to use => When you need to return the selected elements into a new array

11: splice()

The splice() method adds/removes elements to/from an array, and returns the removed elements. It is a very handy method for array elements modifications

splice() is invoked with the following arguments:

  • index - An integer that specifies at what position to add/remove elements, You can use negative values to specify the position from the end of the array
  • howManyToRemove (Optional) - The number of elements to be removed. If set to 0, no elements will be removed
  • item1, ... , itemX (Optional) - The new elements to be added to the array
const fruits1 = ["Banana", "Peach", "Apple", "Mango", "Orange"];

// At position 2, add the new elements and remove 1 item

fruits1.splice(2, 1, "Lemon", "Kiwi");
console.log(fruits1)
// [ 'Banana', 'Peach', 'Lemon', 'Kiwi', 'Mango', 'Orange' ]

// At position 1, remove 2 elements

const fruits2 = ["Banana", "Peach", "Apple", "Mango", "Orange"];
fruits2.splice(1, 2);
console.log(fruits2)
// [ 'Banana', 'Mango', 'Orange' ]

When to use => When you need to add/remove elements to/from an array

12: pop()

The pop() method removes the last element from an array and returns that element. This method changes the length of the array

const animals = ['rat', 'cat', 'bat', 'snake', 'dog'];
console.log(animals.pop());
// "dog"
console.log(animals);
// [ 'rat', 'cat', 'bat', 'snake' ]

When to use => When you need to remove the last element of an array, use the pop() method

13: shift()

The shift() method removes the first element from an array and returns that element. This method changes the length of the array

const animals = ['rat', 'cat', 'bat', 'snake', 'dog'];
console.log(animals.shift());
// "rat"
console.log(animals);
// [ 'cat', 'bat', 'snake', 'dog' ]

When to use => When you need to remove the first element of an array, use the shift() method

14: push()

The push() method adds a new element to the end of an array and returns the new length

const animals = ['rat', 'cat', 'bat', 'snake', 'dog'];
animals.push('bull');
console.log(animals);
// [ 'rat', 'cat', 'bat', 'snake', 'dog', 'bull' ]

When to use => When you need to add an element at the end of an array use push() method

15: unshift()

The unshift() method adds a new element to the beginning of an array and returns the new length

const animals = ['rat', 'cat', 'bat', 'snake', 'dog'];
animals.unshift('bull');
console.log(animals);
// [ 'bull', 'rat', 'cat', 'bat', 'snake', 'dog' ];

When to use => When you need to add an element at the beginning of an array, use unshift() method

If you would like to get notified when a new post is out, subscribe to push notifications by signing in

If you enjoyed the blog post, share it on social media so others can find it!

If you have any questions, suggestions, or feedback, please leave them in the comments below! It would mean the world to me!!!

Related posts

Comments (0)