Tag Archives: map

Understanding Java Script Map, Filter and Reduce

 

The array

// The array
var people = [
{name: 'john', age:24, weight: 84},
{name: 'tim', age:34, weight: 76},
{name: 'Jack', age:26, weight: 65},
];

MAP


// map - use it if I want to do the same operation for each element in the array
// and return the same amount of items in the array.
// array.map(
// current item of the array,
// curent index,
// the entire array
// );
var result = people.map((person, index, persons) => {
return `${person.name}: ${person.age}`;
});
console.log('map', result);

FILTER


// filter - return only items that match certain criteria.
// array.filter(
// current item of the array,
// curent index,
// the entire array
// )

var result = people.filter((person, index, persons) => {
return person.age < 30;
});
console.log('filter', result);

 

REDUCE


// reduce - return something completely new after iteration through each element
// in the array
// array.reduce(
// current value of the end value,
// current item,
// curent index,
// the entire array
// )
var combined_weight = people.reduce((weight, person, index, persons) => {
return weight += person.weight;
}, 0);
console.log('reduce', combined_weight);