Map Function
It returns new array after some modifications iterate over each element.
Example: If you want to Multiply by 2 to every element in array, in simple approach it will look like this
const arr =[1,2,3,4,5]
const newArr =[]
for(let i=0; i<=arr.length-1; i++){
newArr.push(arr[i]*2);
}
console.log(newArr)
And you will get output // 2,4,6,8,10
Same thing using map function you will do it like
const arr = [1,2,3,4,5]
console.log(arr.map(e => e*2))
And you will get same output // 2,4,6,8,10
Reduce Function
This function reduces an array of values down to just one value. To get the output value, it runs a reducer function on each element of the array.
example
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum);
Filter Function
The filter() method takes each element in an array and it applies a conditional statement against it. If this conditional returns true, the element gets pushed to the output array. If the condition returns false, the element does not get pushed to the output array.
Example
const numbers = [1, 2, 3, 4];
const evens = numbers.filter(item => item % 2 === 0);
console.log(evens); // [2, 4]
Comments
Post a Comment