Array Methods You Must Know
Array methods help us perform operations on arrays and modify or process their data more easily.
push()
Adds an element at the end of the array.
const arr = [1, 2];
arr.push(3);
console.log(arr);
Output:
[1, 2, 3]
pop()
Removes the last element from the array.
const arr = [1, 2, 3];
arr.pop();
console.log(arr);
Output:
[1, 2]
unshift()
Adds an element at the beginning of the array.
const arr = [2, 3];
arr.unshift(1);
console.log(arr);
Output:
[1, 2, 3]
shift()
Removes the first element from the array.
const arr = [1, 2, 3];
arr.shift();
console.log(arr);
Output:
[2, 3]
map()
map() is used to iterate through an array and return a new array after performing some operation.
const arr = [1, 2, 3];
const doubled = arr.map((num, index, array) => {
console.log(num, index, array);
return num * 2;
});
console.log(doubled);
Output:
[2, 4, 6]
Parameters available inside map()
num→ current elementindex→ current indexarray→ original array
map() always returns a new array.
filter()
filter() returns elements based on a condition.
const arr = [1, 2, 3, 4];
const even = arr.filter((num, index, array) => {
console.log(num, index, array);
return num % 2 === 0;
});
console.log(even);
Output:
[2, 4]
Parameters available inside filter()
num→ current elementindex→ current indexarray→ original array
reduce()
reduce() loops through the array and reduces it into a single value.
const arr = [1, 2, 3, 4];
const sum = arr.reduce((acc, curr, index, array) => {
console.log(acc, curr, index, array);
return acc + curr;
}, 0);
console.log(sum);
Output:
10
Parameters available inside reduce()
acc→ accumulator (previous returned value)curr→ current elementindex→ current indexarray→ original array
forEach()
forEach() is used to iterate through an array.
const arr = [1, 2, 3];
arr.forEach((num, index, array) => {
console.log(num, index, array);
});
Output:
1
2
3
Parameters available inside forEach()
num→ current elementindex→ current indexarray→ original array