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 initialValue = 10; var combined_weight = people.reduce((weight, person, index, persons) => { return weight += person.weight; }, initialValue); console.log('reduce', combined_weight);
Another example of reduce, that will convert the array of objects, to object of objects, where person.name is going to be the key
var reducer = (accumolator, person) => { accumolator[person.name] = person; return accumolator; } var initialValue = {}; // reduce takes reducer function as first parameter, and initial value var result = people.reduce(reducer, initialValue); console.log('reduce', result);