Map, reduce and filter
JavaScript
//Playing around with http://www.macwright.org/presentations/beyondfor
//Map - turn an array of animals into an array of rockin animals with a named function - creates new array - USE FOR TRANSFORMING VALUES
const animals = ['cats', 'dogs'];
function theyRock (creatures) {
console.log(creatures + ' rock');
}
const rockinAnimals = animals.map(theyRock);
const rockinAnimalsES6 = animals.map((creatures) => creatures + ' rock');
console.log('es6: ' + rockinAnimalsES6);
//Filter - create a new array with animals that pass a test
function thatsACat(animals) {
return animals === 'cats';
}
const catsOnly = animals.filter(thatsACat);
console.log (catsOnly);
const catsOnlyES6 = animals.filter((thatsACat) => thatsACat === 'cats');
console.log('es6: ' + catsOnlyES6);
//Reduce - use for aggregating values
const numbers = [4, 8, 16, 22, 36];
const sum = numbers.reduce (function(currentSum, value) {
return currentSum + value;
}, 0);
//ES6
function addNumbers(numbers) {
console.log (numbers.reduce((currentSum, value) => currentSum + value, 0));
}
addNumbers(numbers);
//chaining - useful for doing many steps quickly without intermediate variables
const rockinCatsOnly = ['cats', 'dogs']
.filter(thatsACat)
.map(theyRock);