28
loading...
This website collects cookies to deliver better user experience
//reducer is the callback function, initialValue is the optional second param
array.reduce(reducer [, initialValue])
function reducer(accumulator, currentValue, currentIndex, array){}
const arr = [1,2,3,4]
//define the reducer function, provide it with its first 2 parameters
//returns the sum of the accumulator and currentValue
const calculateSum = (accumulator, currentValue) => accumulator + currentValue
//apply reducer function to array
arr.reduce(calculateSum)
const calculateSum = (accumulator, currentValue) => {
console.log('accumulator: ', accumulator);
console.log('currentValue:', currentValue);
return accumulator + currentValue;
};
arr.reduce(calculateSum)
arr.reduce(reducer, initialValue)
const arr = [1,2,3,4]
const calculateSum = (accumulator, currentValue) => {
console.log('accumulator: ', accumulator);
console.log('currentValue:', currentValue);
return accumulator + currentValue;
};
//here we tell the reduce method to initialise the accumulator at 10
arr.reduce(calculateSum, 10)
initialValue | accumulator | currentValue |
---|---|---|
not passed | accumulator = array[0] |
currentValue = array[1] |
passed | accumulator = initialValue |
currentValue = array[0] |
{ s: 2, a: 1, v: 1, e: 4, " ": 2, t: 1, h: 1, b: 1 }
const string = "🚫🚫🚀🚀 less rockets, more bees pls"
const letterCountReducer = (acc, value) => {
acc[value] ? ++acc[value] : (acc[value] = 1);
return acc;
};
//the accumulator is initialised as an empty object
[...string].reduce(letterCountReducer, {})
//BOO! An unnatural habitat
const zoo = [
['🐇', '🐇', '🐇'],
['🐷', '🐷', '🐷'],
['🐻', '🐻', '🐻'],
];
const flatten = (acc, animalArray) => acc.concat(animalArray);
zoo.reduce(flatten, []);
//returns ["🐇", "🐇", "🐇", "🐷", "🐷", "🐷", "🐻", "🐻", "🐻"]
//YAY! A natural habitat!
//initial arr
const arrOfDupes = ["🚀", "🚀", "🚀", "🌍"];
//desired output
["🚀", "🌍"];
const dedupe = (acc, currentValue) => {
if (!acc.includes(currentValue)) {
acc.push(currentValue);
}
return acc;
};
const dedupedArr = arrOfDupes.reduce(dedupe, []);
dedupedArr = [...new Set(array)];
//initial array of objects to be grouped
const climateBehaviours = [
{ description: "Recycle", greenPoints: 30 },
{ description: "Cycle everywhere", greenPoints: 40 },
{ description: "Commute to work via plane", greenPoints: -70 },
{ description: "Replace beef with veg", greenPoints: 50 },
{ description: "Build a rocket for space tourism", greenPoints: -500 },
];
//desired output: an object with two groups
{
goodClimateBehaviours: [{}, {}, ...], // greenPoints >= 0
badClimateBehaviours: [{}, {}, ...], // greenPoints < 0
};
//reducer function
const groupBehaviour = (acc, currentObj) => {
currentObj.greenPoints >= 0
? acc.goodClimateBehaviours.push(currentObj)
: acc.badClimateBehaviours.push(currentObj);
return acc;
};
//initial value
const initialGrouping = {
goodClimateBehaviours: [],
badClimateBehaviours: [],
};
//applying the reduce method on the original array
const groupedBehaviours = climateBehaviours.reduce(groupBehaviour, initialGrouping);
console.log(groupedBehaviours)
{
goodClimateBehaviours: [
{ description: "Recycle", greenPoints: 30 },
{ description: "Cycle everywhere", greenPoints: 40 },
{ description: "Replace beef with veg", greenPoints: 50 },
],
badClimateBehaviours: [
{ description: "Commute to work via plane", greenPoints: -70 },
{ description: "Build a rocket for space tourism", greenPoints: -500 },
],
};
const climateActions = [
{
id: 'space_tourism',
description: 'build rockets for space tourism',
outcomes: [
{ outcome: 'rich people can go to space', isDesirable: false },
{ outcome: 'is pretty cool', isDesirable: true },
{ outcome: 'increased emissions', isDesirable: false },
{
outcome: 'investment diverted from green energy to space tourism',
isDesirable: false,
},
],
},
{
id: 'trees_4_lyf',
description: 'stop burning down the amazon',
outcomes: [
{ outcome: 'air for all', isDesirable: true },
{ outcome: 'our kids might live', isDesirable: true },
{
outcome: 'reduce threat of imminent extinction',
isDesirable: true,
},
{
outcome: 'make greta happy',
isDesirable: true,
},
{
outcome: 'make bolsonaro sad',
isDesirable: false,
},
],
},
];
const climateInitiatives = {
'space_tourism': {
badOutcomes: [
'rich people can go to space',
'increased emissions',
'investment diverted from green energy to space tourism',
],
goodOutcomes: ['is pretty cool'],
},
'trees_4_lyf': {
badOutcomes: ['make bolsonaro sad'],
goodOutcomes: [
'air for all',
'our kids might live',
'reduce threat of imminent extinction',
'make greta happy',
],
},
};
const reducer = (acc, currentObj) => {
const newAcc = {
...acc,
[currentObj.id]: { badOutcomes: [], goodOutcomes: [] },
};
currentObj.outcomes.map(outcome => {
outcome.isDesirable
? newAcc[currentObj.id].goodOutcomes.push(outcome.outcome)
: newAcc[currentObj.id].badOutcomes.push(outcome.outcome);
});
return newAcc;
};
const res = climateActions.reduce(reducer, {});
[currentObj.id]: { badOutcomes: [], goodOutcomes: [] }