In JavaScript map, reduce and filter are higher-order function that operate on an array which manipulate and extract values from it
Map()
The map function is used to create a new array by providing the function to each element of array
// Example 1
const originalArray = [10, 20, 30, 40];
const newArray = originalArray.map(function(val){
return val * 10;
});
console.log(newArray) // [100,200,300,400]
//Example 2: Creating a new array containing only odd numbers multiply by 2
const num = [1, 2, 3, 4, 5, 6, 7, 8, 9];
const newVal = num.map((val) => (val % 2 !== 0) ? val * 2 : val);
console.log(newVal); // [2,2,6,4,10,6,14,8,18]
Reduce()
This function is used to reduce the value of elements to a single value by applying specific function
const array = [2,4,6,8];
const initialValue = 0;
const sum = array.reduce(function(accumulator, currentValue) {
return accumulator + currentValue;
}, initialValue);
console.log(sum) // 20
Note: Initially the accumulator takes the value of initialValue (0) after that it will take the value of (accumulator + currentValue). We can pass any specific value of instead of initialValue this way
const Total = array.reduce((acc, currVal) => (acc+currVal), 0)
Filter()
The filter function is used to create a new array that contains only those elements that pass the provided condition
// Example 1: print only those element which are greater than 50
const array1 = [12,34,67,89,98];
const result = array1.filter((val) => val > 50);
console.log(result) // [67,89,98]
// Example 2: print only even number
const numbers = [10, 20, 33, 14, 235];
const evenNumbers = numbers.filter((number) => number % 2 === 0);
conosle.log(evenNumbers) // [10,20,14]
Here is the illustrative example of map
, reduce
and filter
in one array
const numbers = [1,2,3,4,5];
const result = numbers
.filter((value) => value % 2 !== 0) // Filter odd numbers
.map((value) => value * 2) // Double the remaining values
.reduce((accumulator, currentValue) => accumulator + currentValue, 0); // Sum the doubled values
console.log(result); // Output: 18
Let's Connect
If you like this article lets connect on LinkedIn https://www.linkedin.com/in/shivamgupta6418/