Array -> forEach(), map(), filter(), reduce()

Fatima Alam - Nov 30 '23 - - Dev Community

refer -> https://www.freecodecamp.org/news/javascript-map-reduce-and-filter-explained-with-examples/

map()
Syntax
var new_array = arr.map(function callback(element, index, array) {
// Return value for new_array
}[, thisArg])

filter()
Syntax
var new_array = arr.filter(function callback(element, index, array) {
// Return true or false
}[, thisArg])

reduce()
const numbers = [1, 2, 3, 4];
const sum = numbers.reduce(function (result, item) {
return result + item;
}, 0);
console.log(sum); // 10

Here, 0 is the default value for result variable.

let a = [1,2,3,4,5,6,7,8,9,10];

let sum1 = a.reduce((acc, item)=>{
  return acc+item;
}, 0);

console.log(sum1);
Enter fullscreen mode Exit fullscreen mode

Here is the difference ->

const numbers = [1, 2, 3, 4];
const doubled = numbers.map(item => item >= 2);
const doubled2 = numbers.filter(item => item >= 3);
const doubled3 = numbers.reduce(
(accumulator, item) => accumulator = item>=3,
0,
);
console.log(doubled); // [2, 4, 6, 8]
console.log(doubled2);
console.log(doubled3);

Output->
[false, true, true, true]0: false1: true2: true3: truelength: 4[[Prototype]]: Array(0)
a.js:6 (2) [3, 4]
true

Difference between forEach() and map() ->
since forEach returns undefined and map returns entire modified array so the later can be used in chaining.

why don't we use a normal function instead of filter and map and reduce =>
Because these prove useful while chaining as they return the answer and in reduce we need to declare an empty accumulator in order to store the intermediate results in a normal function but it's defined already in case of a reduce function.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player