DEV Community

Cover image for Array Methods You Must Know
Soubhagya Dash
Soubhagya Dash

Posted on

Array Methods You Must Know

Today, we’re going to explore some of the most commonly used array methods with suitable examples and visually understand how each method works.

The methods we're going to cover are:-

  1. push() and pop()
  2. shift() and unshift()
  3. map()
  4. filter()
  5. reduce()
  6. foreach()

Let's get started with the first one:-

1. push() and pop()

Using these two methods makes easy to add or remove elements from the end of an array.

push() :-

Using push() method we can add an element in the end of an array.

Let's take an real life example to understand how it works:-

I am a shoe-obsessed person . So, I have a collection of shoes from different brands (Puma, Nike, and Adidas) in my shoe rack.

let myShoeCollection = ["Puma", "Nike", "Adidas"]

console.log(myShoeCollection)        // [ 'Puma', 'Nike', 'Adidas' ]
Enter fullscreen mode Exit fullscreen mode

However recently 'One8' launched it's shoes with the signature of Virat Kohli. So I couldn’t ignore them for too long and finally purchased a pair 🤩. Now I have to keep them in my shoe rack. So i just have to do it like:-

let myShoeCollection = ["Puma", "Nike", "Adidas"]

myShoeCollection.push("One8")

console.log(myShoeCollection)    // [ 'Puma', 'Nike', 'Adidas', 'One8' ]
Enter fullscreen mode Exit fullscreen mode

So, here, we've added 'One8' in the end of myShoeCollection using the push() method.

pop() :-

Using pop() method, we can remove an element from the end of an array. It's the exact opposite of push method.

let's continue the same story:-

After a few days, my friend asks me to borrow the 'One8' shoes for a date. So i just have to take the shoes out of the shoe rack. So i can do it like this:-

let myShoeCollection = ["Puma", "Nike", "Adidas", "One8"]
console.log(myShoeCollection)      // [ 'Puma', 'Nike', 'Adidas', 'One8' ]

myShoeCollection.pop()
console.log(myShoeCollection)      // [ 'Puma', 'Nike', 'Adidas']
Enter fullscreen mode Exit fullscreen mode

Javascript will automatically remove the last element of myShoeCollection. We don't have to mention the element's name inside the parentheses. So, here, we've removed an element from the last of an array using pop() method.

2. shift() and unshift()

Using these two methods makes easy to add or remove elements from the start of an array.

shift() :-

Using shift() method, we can remove only the first element of an array.

Let's take an real life example to understand how it works:-

Imagine that you are distributing prasad in a temple. Many devotees are standing in line, waiting for their turn to receive the prasad.

let turnForPrasad = ["Ali", "Karan", "Swayam", "Ayesha"]

console.log(turnForPrasad)    // [ 'Ali', 'Karan', 'Swayam', 'Ayesha' ]
Enter fullscreen mode Exit fullscreen mode

Now you witness that Ali said something disrespectfully about God. So, you decide to remove him from the line without giving him the prasad. You can do something like this:-

let turnForPrasad = ["Ali", "Karan", "Swayam", "Ayesha"]

let removedPerson = turnForPrasad.shift()

console.log(turnForPrasad)    // [ 'Karan', 'Swayam', 'Ayesha' ]
console.log(removedPerson)    // Ali
Enter fullscreen mode Exit fullscreen mode

Without giving the element's name, javascript will remove the first element from turnForPrasad and the other elements will shift to their previous positions.

In the above example, we've stored the removed element in a variable named removedPerson so that we can see what was actually removed.

So, here, we've removed an element from the beginning of an array using the shift() method.

unshift() :-

Using unshift() method, we can add elements in the beginning of an array. It's the exact opposite of shift method.

Let's continue to the story again:-

Now, you see that two people with disabilities are standing in line for prasad. You are a warm-hearted person, so you don't want to see them struggle for so long. That's why you decide to let them move to the front of the line. So, you can do it like:-

let turnForPrasad = ["Karan", "Swayam", "Ayesha"]

turnForPrasad.unshift("PWD-1", "PWD-2")   // PWD means person with disability

console.log(turnForPrasad)    // [ 'PWD-1', 'PWD-2', 'Karan', 'Swayam', 'Ayesha' ]

Enter fullscreen mode Exit fullscreen mode

So, here, we've added 'PWD-1' & 'PWD-2' in the beginning of turnForPrasad using the unshift() method. You can push as many elements as you want.

3. map():-

Using the map() method, we can perform an operation on each element of an array. The main thing to remember is that after performing the given operation, the map() method stores the changed elements in a new array, while the original array remains unchanged.

Let's see how it works though:-

let myArray = [20, 6, 18, 9, 13]
console.log("Before map:", myArray)         // Before map: [ 20, 6, 18, 9, 13 ]

let doubledValue = myArray.map(function(num){
    return num * 2;
})

console.log("After map:", myArray);        // After map: [ 20, 6, 18, 9, 13 ]
console.log("New doubled array", doubledValue);       // New doubled value [ 40, 12, 36, 18, 26 ]

Enter fullscreen mode Exit fullscreen mode

Let's understand the map() method with a real-life example:

Imagine you have an array containing some amounts in US Dollars ($). For some business purpose, you want to convert each amount from US Dollars ($) to Indian Rupees (INR).

This is where the map() method can help you:

let inDollar = [20, 6, 18, 9, 13]
console.log("Cash In Dollar:", inDollar)         // Cash In Dollar: [ 20, 6, 18, 9, 13 ]

let inINR = inDollar.map(function(num){
    return num * 96;                         // 1 dollar = 96.25 INR
})

console.log("Cash In INR", inINR);         // Cash In INR [ 1920, 576, 1728, 864, 1248 ]
Enter fullscreen mode Exit fullscreen mode

4. filter():-

Using the filter() method, we can select specific elements from an array based on a given condition. The elements that satisfy the condition are stored in a new array, while the original array remains unchanged.

let's see how it works:-

let randomNumbers = [5, 10, 15, 20, 25]
console.log("Before filter:", randomNumbers)       // Before filter: [ 5, 10, 15, 20, 25 ]

let aboveTen = randomNumbers.filter(function(num){
    return num > 10;                         
})

console.log("After filter:", randomNumbers)        // After filter: [ 5, 10, 15, 20, 25 ]
console.log("Numbers above 10 are:", aboveTen);     // Numbers above 10 are: [ 15, 20, 25 ]
Enter fullscreen mode Exit fullscreen mode

Let's move on to a real-life example:

Imagine you are an English teacher, and you have the results of all your students in an array. Now, you want to find out which students scored 75 or more than 75.

You can do it like this:

let marks = [62, 80, 75, 28, 95]
console.log("Marks In English", marks)       // Marks In English [ 62, 80, 75, 28, 95 ]

let above75 = marks.filter(function(num){
    return num >= 75;                         
})

console.log("marks above 75 are:", above75);     // marks above 75 are: [ 80, 75, 95 ]
Enter fullscreen mode Exit fullscreen mode

5. reduce():-

Using the reduce() method, you can combine all the elements of an array and turn them into a single value. The original array remains unchanged like map() & filter(), and the final result will be returned by reduce().

Let's take an example and understand it line by line.

let randomNumber = [10, 20, 30, 40]
console.log("Before reduce:", randomNumber)         // Before reduce: [ 10, 20, 30, 40 ]

let totalNumber = randomNumber.reduce(function(accumulator, currentValue){
    return accumulator + currentValue;                         
}, 0)

console.log("After reduce:", randomNumber)         // After reduce: [ 10, 20, 30, 40 ]
console.log("Addition of each number is:", totalNumber);         // Addition of each number is: 100
Enter fullscreen mode Exit fullscreen mode

Steps how a reduce() works:-

  1. When we use the reduce() method on randomNumber, which is an array, reduce() will start with [10, 20, 30, 40].
  2. We have to give an initial value from where we want to start the calculation. Here, 0 becomes the initial value of the accumulator.
  3. reduce() will go to the first value (10) of the given array and store it in currentValue. Then, it adds it to the accumulator value (0 + 10 = 10).
  4. Now, the accumulator will be updated to 10.
  5. Then, reduce() will go to the 2nd element (20) of the array, and currentValue will be updated to 20. Then, it adds it to the accumulator (10 + 20 = 30), and so on...
  6. After the last element (40) of the array performs the operation, reduce() returns the final result, which is stored in the accumulator.

Let's dry-run the code to better understand what's happening with reduce():-

Accumulator Current Value Operation Accumulator = New Total
0 10 0 + 10 10
10 20 10 + 20 30
30 30 30 + 30 60
60 40 60 + 40 100

Now move on to a real-life example:-

let, you are now shopping in Zudio and you've decided to take a linen shirt, a straight fit jeans, a pair of chelsea shoe and a perfume. You can calculate it like:-

const cart = [599, 799, 1049, 299];

const totalPrice = cart.reduce(function(acc, curr) {
    return acc + curr
} , 0);

console.log("Total price:",totalPrice);          // Total price: 2746
Enter fullscreen mode Exit fullscreen mode

6. forEach():-

Using the forEach() method, we can loop through every element of an array. You don't have to declare an initial value, use an increment operator, or set a condition. forEach() automatically loops through every element of the given array.

Let's see the workflow of forEach():-

forEach() doesn't return a new array or the result of the function, that's why if you try to store it's result in a variable, you'll get undefined. So don't use forEach() like this:-

let myArray = [10, 20, 30, 40];

let printedArray = myArray.forEach(function (val) {
    console.log("Adding 5 to every element:", val + 5);
});

console.log(printedArray);     // undefined
Enter fullscreen mode Exit fullscreen mode

The correct way to write forEach() is:-

let myArray = [10, 20, 30, 40];

myArray.forEach(function (val) {
    console.log("Adding 5 to every element:", val + 5);
});

console.log("After operation:", myArray)       // After operation: [ 10, 20, 30, 40 ]
Enter fullscreen mode Exit fullscreen mode

Let's move on to a real-life example:-

Today, you decide to buy some fruits (apples, oranges, mangoes, and litchis). So, you go to a fruit store in your local market and tell the shopkeeper:

let fruits = ["Apple", "Oranges", "Mango", "Lichi"]

fruits.forEach(function(fruit) {
    console.log("Give me 1kg of:", fruit)
})

/*
Give me 1kg of: Apple
Give me 1kg of: Oranges
Give me 1kg of: Mango
Give me 1kg of: Lichi
*/
Enter fullscreen mode Exit fullscreen mode

for loop vs map/filter :-

The methods we discussed above can also be used to achieve the same things with loops.

So, you might think:

Why do we have to use methods instead?

Let's see how these methods reduce verbosity and make JavaScript a lot easier to write and understand.

Case 1

You have given an assignment that "double each number of a given array".
Using for loop you'll do like this:-

let givenArray = [10, 15, 20, 30]
let doubledArray = []

for (let i = 0; i < givenArray.length; i++) {
    doubledArray.push(givenArray[i] * 2)
}

console.log(doubledArray);
Enter fullscreen mode Exit fullscreen mode

Instead of writing this much code, you can simply use map() method:-

let givenArray = [10, 15, 20, 30]

let doubledArray = givenArray.map(num => num * 2)     // Here this is written as an arrow function.

console.log(doubledArray);     // [ 20, 30, 40, 60 ]
Enter fullscreen mode Exit fullscreen mode

Case 2

Now the assignment is "filter out numbers greater than 10".
Let's see using for loop:-

let numbers = [10, 404, 18, 5, 101];
let filteredNumbers = [];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] > 10) {
    filteredNumbers.push(numbers[i]);
  }
}

console.log(filteredNumbers);       // [ 404, 18, 101 ]
Enter fullscreen mode Exit fullscreen mode

Now using filter() method:-

let numbers = [10, 404, 18, 5, 101];

let filteredNumber = numbers.filter(num => num > 10);   // using arrow function

console.log(filteredNumber);      // [ 404, 18, 101 ]
Enter fullscreen mode Exit fullscreen mode

See how much cleaner and more readable the code becomes with array methods. Hopefully, by now, you have a better understanding of the importance of these methods.

Important Tips for Beginners

  1. Try everything in the console - Open your browser's developer tools (F12) and test these methods yourself. See what happens!

  2. Don't chain methods initially - Write them step by step. Once you're comfortable, you can do things like:

let result = numbers
     .filter(num => num > 10)
     .map(num => num * 2);
Enter fullscreen mode Exit fullscreen mode
  1. Remember what each method returns:
  • push/pop/shift/unshift → change original array
  • forEach → nothing (undefined), just performs action
  • map → new array of same length
  • filter → new array (may be shorter)
  • reduce → single value
  1. Original array remains unchanged for map, filter, and reduce - they create new arrays/values.

Overview:-

Method What it does Returns Changes original?
push() Adds to end New length Yes
pop() Removes from end Removed element Yes
shift() Removes from start Removed element Yes
unshift() Adds to start New length Yes
forEach() Does something for each undefined No
map() Transforms each item New array No
filter() Keeps items that pass test New array No
reduce() Combines all items Single value No

Conclusion

Array methods are like special tools in your JavaScript toolbox. Instead of building everything from scratch with loops, you can use these methods to write cleaner, more readable code.

Remember:

  • push/pop and shift/unshift are for adding/removing items
  • forEach is for doing something with each item
  • map is for transforming each item into something new
  • filter is for picking only certain items
  • reduce is for combining everything into one value

The more you practice these, the more natural they'll become. Soon you'll find yourself reaching for these methods automatically instead of writing loops!

Pro tip: Keep your browser console open while coding and test each method as you learn. See what happens when you use them with different arrays.

_______________________________ X _______________________________

Hope you liked this blog. If there's any mistake or something I can improve, do tell me. You can find me on LinkedIn and X, I post more stuff there.

That’s it for Today! It was a good learning session. Now, time to move on to the next concept.✌️

Top comments (0)