Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know

Published
11 min read

Introduction

Imagine you have a list of tasks written on paper. Instead of rewriting the list each time you want to make changes, you could use a pen to cross out completed tasks, add new tasks, or reorganize them. Array methods in JavaScript work the same way. They are built-in tools that let you easily manipulate arrays without rewriting them from scratch.

In this blog, we will learn the most important array methods that you will use every day: push(), pop(), shift(), unshift(), map(), filter(), reduce(), and forEach().


1. push() and pop()

These methods are used to add and remove elements from the end of an array.

push() - Adding Elements to the End

The push() method adds one or more elements to the end of an array. It modifies the original array.

Syntax

arrayName.push(element1, element2, ...);

Example 1: Adding a Single Element

let fruits = ["Apple", "Banana", "Mango"];

console.log("Before push: ", fruits);
// Output: Before push: ["Apple", "Banana", "Mango"]

fruits.push("Orange");

console.log("After push: ", fruits);
// Output: After push: ["Apple", "Banana", "Mango", "Orange"]

Example 2: Adding Multiple Elements

let numbers = [1, 2, 3];

console.log("Before: ", numbers); // Output: Before: [1, 2, 3]

numbers.push(4, 5, 6);

console.log("After: ", numbers); // Output: After: [1, 2, 3, 4, 5, 6]

Example 3: push() Returns the New Length

let marks = [85, 90];

let newLength = marks.push(92);

console.log("New length: " + newLength); // Output: New length: 3
console.log("Marks: ", marks); // Output: Marks: [85, 90, 92]

pop() - Removing Elements from the End

The pop() method removes the last element from an array. It returns the removed element.

Syntax

arrayName.pop();

Example 1: Removing the Last Element

let fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log("Before pop: ", fruits);
// Output: Before pop: ["Apple", "Banana", "Mango", "Orange"]

let removed = fruits.pop();

console.log("Removed fruit: " + removed); // Output: Removed fruit: Orange
console.log("After pop: ", fruits);
// Output: After pop: ["Apple", "Banana", "Mango"]

Example 2: pop() on Empty Array

let emptyArray = [];

let result = emptyArray.pop();

console.log("Result: " + result); // Output: Result: undefined

When you pop from an empty array, you get undefined.


2. shift() and unshift()

These methods add and remove elements from the beginning of an array.

shift() - Removing Elements from the Beginning

The shift() method removes the first element from an array. It returns the removed element.

Syntax

arrayName.shift();

Example: Removing the First Element

let fruits = ["Apple", "Banana", "Mango", "Orange"];

console.log("Before shift: ", fruits);
// Output: Before shift: ["Apple", "Banana", "Mango", "Orange"]

let removed = fruits.shift();

console.log("Removed fruit: " + removed); // Output: Removed fruit: Apple
console.log("After shift: ", fruits);
// Output: After shift: ["Banana", "Mango", "Orange"]

unshift() - Adding Elements to the Beginning

The unshift() method adds one or more elements to the beginning of an array.

Syntax

arrayName.unshift(element1, element2, ...);

Example 1: Adding a Single Element to the Beginning

let fruits = ["Banana", "Mango", "Orange"];

console.log("Before unshift: ", fruits);
// Output: Before unshift: ["Banana", "Mango", "Orange"]

fruits.unshift("Apple");

console.log("After unshift: ", fruits);
// Output: After unshift: ["Apple", "Banana", "Mango", "Orange"]

Example 2: Adding Multiple Elements to the Beginning

let numbers = [4, 5, 6];

console.log("Before: ", numbers); // Output: Before: [4, 5, 6]

numbers.unshift(1, 2, 3);

console.log("After: ", numbers); // Output: After: [1, 2, 3, 4, 5, 6]

Comparison: push/pop vs shift/unshift

Method Position Adds/Removes Speed
push() End Adds Fast
pop() End Removes Fast
unshift() Beginning Adds Slow
shift() Beginning Removes Slow

(Note: shift and unshift are slower because they need to reorganize all element indices)


3. map()

The map() method creates a new array by applying a function to each element of an existing array. It does NOT modify the original array.

Syntax

const newArray = arrayName.map(function(element) {
  return transformedElement;
});

Or with arrow functions:

const newArray = arrayName.map(element => transformedElement);

How map() Works

For each element in the array, map() calls your function, collects the results, and returns a new array.

Original Array: [1, 2, 3, 4, 5]
                 |  |  |  |  |
              Function applied to each element (double each element)
                 |  |  |  |  |
New Array:     [2, 4, 6, 8, 10]

Example: Doubling Numbers

Traditional for loop approach:

let numbers = [1, 2, 3, 4, 5];
let doubled = [];

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

console.log("Original: ", numbers); // Output: Original: [1, 2, 3, 4, 5]
console.log("Doubled: ", doubled);  // Output: Doubled: [2, 4, 6, 8, 10]

Using map():

let numbers = [1, 2, 3, 4, 5];

let doubled = numbers.map(num => num * 2);

console.log("Original: ", numbers); // Output: Original: [1, 2, 3, 4, 5]
console.log("Doubled: ", doubled);  // Output: Doubled: [2, 4, 6, 8, 10]

Important: Original Array Is NOT Modified

let numbers = [1, 2, 3];

let doubled = numbers.map(num => num * 2);

console.log("Original: ", numbers); // Output: Original: [1, 2, 3] (unchanged!)
console.log("Doubled: ", doubled);  // Output: Doubled: [2, 4, 6]

4. filter()

The filter() method creates a new array containing only elements that pass a test. If the test returns true, the element is included. If it returns false, it is excluded.

Syntax

const filteredArray = arrayName.filter(function(element) {
  return condition; // return true or false
});

Or with arrow functions:

const filteredArray = arrayName.filter(element => condition);

How filter() Works

For each element, filter() checks if your condition is true. Only elements that pass are included in the new array.

Code

Original Array: [1, 2, 3, 4, 5, 6]
                 |  |  |  |  |  |
              Filter (keep if even)
                 |        |        |
New Array:     [2,        4,       6]

Example: Filtering Even Numbers

Traditional for loop approach:

let numbers = [1, 2, 3, 4, 5, 6];
let evenNumbers = [];

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    evenNumbers.push(numbers[i]);
  }
}

console.log("All numbers: ", numbers); // Output: All numbers: [1, 2, 3, 4, 5, 6]
console.log("Even numbers: ", evenNumbers); // Output: Even numbers: [2, 4, 6]

Using filter():

let numbers = [1, 2, 3, 4, 5, 6];

let evenNumbers = numbers.filter(num => num % 2 === 0);

console.log("All numbers: ", numbers); // Output: All numbers: [1, 2, 3, 4, 5, 6]
console.log("Even numbers: ", evenNumbers); // Output: Even numbers: [2, 4, 6]

Important: Original Array Is NOT Modified

let numbers = [1, 2, 3, 4, 5];

let evenNumbers = numbers.filter(num => num % 2 === 0);

console.log("Original: ", numbers); // Output: Original: [1, 2, 3, 4, 5] (unchanged!)
console.log("Filtered: ", evenNumbers); // Output: Filtered: [2, 4]

5. reduce()

The reduce() method combines all elements in an array into a single value. It "reduces" the array to one value.

Syntax

const result = arrayName.reduce(function(accumulator, currentElement) {
  return updatedAccumulator;
}, initialValueOfAccumulator);

Or with arrow functions:

const result = arrayName.reduce((acc, current) => acc + current, 0);

How reduce() Works

Think of reduce() as a way to combine all numbers in a list into one result.

Array: [1, 2, 3, 4, 5]

Step 1: acc = 0, current = 1 → acc = 0 + 1 = 1
Step 2: acc = 1, current = 2 → acc = 1 + 2 = 3
Step 3: acc = 3, current = 3 → acc = 3 + 3 = 6
Step 4: acc = 6, current = 4 → acc = 6 + 4 = 10
Step 5: acc = 10, current = 5 → acc = 10 + 5 = 15

Final Result: 15

Example 1: Sum All Numbers

Traditional for loop approach:

let numbers = [1, 2, 3, 4, 5];
let sum = 0;

for (let i = 0; i < numbers.length; i++) {
  sum = sum + numbers[i];
}

console.log("Sum: " + sum); // Output: Sum: 15

Using reduce():

let numbers = [1, 2, 3, 4, 5];

let sum = numbers.reduce((acc, num) => acc + num, 0);

console.log("Sum: " + sum); // Output: Sum: 15

Understanding reduce() Better

The second parameter (after the function) is the initial value:

let numbers = [1, 2, 3];

// Without initial value
let sum1 = numbers.reduce((acc, num) => acc + num);
console.log(sum1); // Output: 6
// acc starts with the first element (1), then adds 2, then 3

// With initial value 10
let sum2 = numbers.reduce((acc, num) => acc + num, 10);
console.log(sum2); // Output: 16
// acc starts with 10, then adds 1, 2, 3

6. forEach()

The forEach() method runs a function for each element in an array. It is simpler than for loop but does NOT create a new array.

Syntax

arrayName.forEach(function(element) {
  // Do something with element
});

Or with arrow functions:

arrayName.forEach(element => {
  // Do something with element
});

Example 1: Printing All Elements

Traditional for loop:

let fruits = ["Apple", "Banana", "Mango"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Output:

Apple
Banana
Mango

Using forEach():

let fruits = ["Apple", "Banana", "Mango"];

fruits.forEach(fruit => console.log(fruit));

Same output, much cleaner!

Example 2: forEach() with Index

You can also access the index and the array itself:

let fruits = ["Apple", "Banana", "Mango"];

fruits.forEach(function(fruit, index) {
  console.log((index + 1) + ". " + fruit);
});

Output:

1. Apple
2. Banana
3. Mango

Example 3: Modifying Array Elements

let prices = [100, 200, 150];

console.log("Original: ", prices); // Output: Original: [100, 200, 150]

prices.forEach((price, index, array) => {
  array[index] = price * 1.10; // Add 10% to each price
});

console.log("After 10% increase: ", prices);
// Output: After 10% increase: [110, 220, 165]

Example 4: Calculating Total

let marks = [85, 90, 78, 92, 88];
let total = 0;

marks.forEach(mark => {
  total = total + mark;
});

console.log("Total marks: " + total); // Output: Total marks: 433

Important: forEach() Does NOT Return a New Array

Unlike map() and filter(), forEach() does NOT create a new array. It just performs actions on each element.


Comparison of Array Methods

When to Use Each Method

Method Purpose Returns Modifies Original
push() Add to end New length Yes
pop() Remove from end Removed element Yes
shift() Remove from beginning Removed element Yes
unshift() Add to beginning New length Yes
map() Transform each element New array No
filter() Keep elements that pass test New array No
reduce() Combine into single value Single value No
forEach() Do something with each element undefined No

Summary

  1. push() and pop() add and remove elements from the end

  2. shift() and unshift() add and remove elements from the beginning

  3. map() transforms each element and returns a new array

  4. filter() keeps only elements that pass a test and returns a new array

  5. reduce() combines all elements into a single value

  6. forEach() runs a function for each element (no new array)

  7. Methods like map(), filter(), reduce() do NOT modify the original array

  8. Methods like push(), pop(), shift(), unshift() DO modify the original array

  9. Use map() when you want to transform data

  10. Use filter() when you want to select data

  11. Use reduce() when you want to combine data

  12. Use forEach() when you want to do something for each element