Array methods you must know

If you have ever written a for loop then we are ready to go with the concept of Array and it's methods.
We have several methods of Array which we will be covering in this blog like :
push() and pop()
shift() and unshift()
map()
filter()
reduce()
forEach()
push( ) and pop( )
- push() - adding to the end of an Array and returning a new array
const flowers = ["Sunflower", "Marigold", "Daffodil"];
console.log(flowers);
// Output is ["Sunflower", "Marigold", "Daffodil"]
flowers.push("Rose");
console.log(flowers);
//Output is ["Sunflower", "Marigold", "Daffodil", "Rose"];
- pop() - removing the last element of an Array and returning a new array.
const flowers = ["Sunflower", "Marigold", "Daffodil"];
console.log(flowers);
// Output is ["Sunflower", "Marigold", "Daffodil"]
flowers.pop();
console.log(flowers);
//Output is ["Sunflower", "Marigold"];
If we have an empty array and we pun the pop() method we will get undefined.
shift( ) and unshift( )
shift() - removes the first element of an Array.
const flowers = ["Sunflower", "Marigold", "Daffodil"];
console.log(flowers);
// Output is ["Sunflower", "Marigold", "Daffodil"]
flowers.shift();
console.log(flowers);
//Output is ["Marigold", "Daffodil", "Rose"];
unshift() - adding a new element at the first of an Array.
const flowers = ["Sunflower", "Marigold", "Daffodil"];
console.log(flowers);
// Output is ["Sunflower", "Marigold", "Daffodil"]
flowers.unshift("Rose");
console.log(flowers);
//Output is ["Rose", "Sunflower", "Marigold", "Daffodil"];
map( )
map() - creates a new array by applying a function to each element. It does not mutate the original array.
const numbers = [1,2,3,4];
console.log(numbers);
// Output is [1,2,3,4]
const double = numbers.map((num) => {
return num * 2;
});
console.log(double);
//Output is [2,4,6,8]
filter( )
filter() - It keeps the only data which matches a certain conditions.
const numbers = [25,10,30,15,35];
console.log(numbers);
//Output is [25,10,30,15,35]
const bigger = numbers.filter((num)=>{
return n > 10;
}
console.log(bigger);
//Output is [25,30,15,35]
reduce( )
reduce() - it turns a bigger or a large value to a single value by adding them or the product or by concatenating them.
const number = [1,2,3,4];
console.log(number);
// Output is [1,2,3,4]
const newnum = number.reduce((sum, num)=>{
sum + num;
},0);
console.log(newnum);
The first argument is a callback: ( sum , num ) => sum + current
sum is the accumulator (starts at 0).
num is the current array element.
forEach( )
forEach() - calls a function once for each element, but it does not return a new array.
const number = [1,2,3,4];
console.log(number);
// Output is [1,2,3,4]
number.forEach((n) =>{
return `Number ${n}`;
})
forEach is great for side effect (logging, DOM updates, calling APIs), while map, filter and reduce are better for transforming or summarizing data.
Comments
Join the discussionNo comments yet. Be the first to comment.




