Skip to main content
0:00est. 5 min

Map For Each Filter Reduce

// https://medium.com/poka-techblog/simplify-your-javascript-use-map-reduce-and-filter-bd02c593cc2d


let arr = [1,2,3,4,5];
// forEach() — executes a provided function once for each array element.

arr.forEach((num, index) => {
arr[index] = num*2
})
console.log(arr);
// map() — creates a new array with the results of calling a provided function on every element in the calling array.

arr = [1,2,3,4,5];

let doubled = arr.map((num) => num*2)

console.log(doubled);

// And map() might be preferable when changing or altering data.
// Not only is it faster but it returns a new Array.
// This means we can do cool things like chaining on other methods ( map(), filter(), reduce(), etc.)

let arr2 = arr.map((num) => num*2).filter((num) => num > 5);

console.log(arr2);

// Just like .map(), .reduce() also runs a callback for each element of an array.
// What’s different here is that reduce passes the result of this callback (the accumulator) from one array element to the other.
// The accumulator can be pretty much anything (integer, string, object, etc.) and must be instantiated or passed when calling .reduce().

var pilots = [
{
id: 10,
name: "Poe Dameron",
years: 14,
},
{
id: 2,
name: "Temmin 'Snap' Wexley",
years: 30,
},
{
id: 41,
name: "Tallissan Lintra",
years: 16,
},
{
id: 99,
name: "Ello Asty",
years: 22,
}
];

// We need to know the total years of experience of all of them. With .reduce(), it’s pretty straightforward:
let total = pilots.reduce((function (acc, pilots) {
return acc+pilots.years;
}),0)

console.log(total);