Header Ads

Header ADS

What is Advanced Arrays [ MFR ] -> map, filter, Reduce in javascript

Example of simple array

const array = [1, 2, 3, 4, 5];
 
const double = [];
const newArray = array.forEach((num) => {
  double.push(num * 2);
});
 
console.log('forEach', double);

Output: forEach [2, 4, 6, 8, 10]


What is the Map function?
You have to always return something on the map (mandatory),
It is used to iterate over an array and call a function on every element of the array.
Example:
const mapArray = array.map((num) => {
  return num * 2;
});
 
console.log('map', mapArray);

Output: map [2, 4, 6, 8, 10]


What is the Filter function?
Filtering our array with a condition.

Example:
const filterArray = array.filter((num) => {
  return num < 5;
});
 
console.log('filter', filterArray);

Output: filter [1,2,3,4]

What is Reduce function?
We can do both filtering and mapping with reduce.
what is an accumulator? -> It is something where we can store the information, that happens in the body of the function.
 
Example:
const reduceArray = array.reduce((accumulator, num) => {
  return accumulator + num;
}, 5);
 
console.log('reduce', reduceArray);

Output: reduce 20

No comments

Powered by Blogger.