Defining Parameters In Javascript Reduce
Solution 1:
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. from MDN.
So it is just an accumulator, or a "current state" value. For example, let's find the maximum value of an array:
let values=[4,5,6,77,8,12,0,9];
let max=values.reduce((acc,curr) => {
console.log(`comparing ${acc} and ${curr}`);
returnMath.max(acc,curr)
},0);
console.log(max);
This code just stores (accumulates) the maximum value found in each step, and then returns it.
Solution 2:
First from MDN a quick description:
The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
Practically:
arr.reduce(callback[, initialValue])
where callback takes (accumulator, currentValue)
as arguments. The accumulator is the holding array for your reduced values, currentValue is the value of the current array index you are comparing.
In your example:
// Reducer function, returns either the current state of the accumulator
//orreturns a newarray instance of the accumulator with the newvalue
const getDistinctColors = (accumulator, currentValue) => ((accumulator.indexOf(currentValue) !==-1) ? accumulator : [ ...accumulator, currentValue ]);
//define color group
let colors = ['red', 'red', 'green', 'blue', 'green'];
// reduce color group (initialize withemptyarray [])
let distinctColors = colors.reduce(getDistinctColors, []);
Post a Comment for "Defining Parameters In Javascript Reduce"