Skip to content Skip to sidebar Skip to footer

Defining Parameters In JavaScript Reduce

I am looking at this reduce function in JavaScript . . . var colors = ['red', 'red', 'green', 'blue', 'green']; var distinctColors = colors.reduce( (distinct, color) =>

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}`); 
  return Math.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
// or returns a new array instance of the accumulator with the new value
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 with empty array [])
let distinctColors = colors.reduce(getDistinctColors, []);

Post a Comment for "Defining Parameters In JavaScript Reduce"