Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know

Updated
2 min readView as Markdown

In this blog, we’ll explore some essential array methods:

  • push() and pop()

  • shift() and unshift()

  • map()

  • filter()

  • reduce() (basic idea)

  • forEache()

1. push() and pop()

push()

Code:

The push() method is used to add an element to the array.

let numbers = [10,20,30];

numbers.push(40);

Before:

[10,20,30]

After:

[10,20,30,40]

pop()

Code:

The pop() method is used to remove the last element form an array.

let numbers =[10,20,30];

numbers.pop();

Before:

[10,20,30]

After:

[10,20]

2. shift() and unshift()

shift()

Code:

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

let numbers =[10,20,30];

numbersshift();

Before:

[10,20,30]

After:

[20,30]

unshift()

Code:

The unshift() method adds an element to the beginning of an array.

let numbers =[10,20,30];

numbers.unshift(5);

Before:

[10,20,30]

After:

[5,10,20,30]

3. forEach()

Code:

The forEach() method is used to loop through each element of an array.

let numbers =[1,2,3];

numbers.forEach(function(num){

console.log(num);

}

This will print:

1

2

3

4. map()

The map() method is used to create a new array by modifying each element of the original array.

Traditional for loop approach:

Code:

let numbers = [1,2,3];

let doubled = [];

for (let i = 0; i < numbers.length; i++) {

doubled.push(numbers[i] * 2);

}

Result:

[2,4,6]

Using map():

Code:

let numbers =[1,2,3];

let doubled =numbers.map(function(num)){

return num * 2;

});

Result:

[2,4,6]

5. filter()

The filter() method is used to select specific elements based on a condition.

Traditional for loop approach:

Code:

let numbers = [5,10,15,20];

let result =[];

for(let i = 0; i < numbers.length; i++){

if(numbers[i] > 10 {

result.push(numbers[i]);

}

}

Result:

[15,20]


Using filter():

Code:

let numbers = [5,10,15,20];

let result = numbers.filter(function(num){

return num > 10;

});

Result:

[15,20]


🔹 6. reduce() (Basic Explanation)

The reduce() method is used to combine all elements of an array into a single value, such as calculating the total sum.

Code:

let numbers =[10,20,30];

let total = numbers.reduce(function(sum,num) {

return sum + num;

}

Result:

60

Here:

  • "sum" stores the accumulated result

  • "num "represents the current element