4

I am looking at this reduce function in JavaScript . . .

var colors = ['red', 'red', 'green', 'blue', 'green'];

var distinctColors = colors.reduce(
    (distinct, color) =>
        (distinct.indexOf(color) != -1) ?
            distinct : 
            [...distinct, color],
    []
)

I understand that the callback function is called once for each item in the colors array, searching for the color string in distinct and simply returning the array if it is found, and adding color to distinct if not found.

What I do not understand is how the function parameters (distict, color) are defined as the empty array and each color.

Does JavaScript automatically assume that distinct is the array because I call distinct.indexOf(color)??

3
  • 2
    See that last part, that ,[] - the second parameter you pass to reduce is the type of distinct - per the docs: [Optional] Value to use as the first argument to the first call of the callback. If no initial value is supplied, the first element in the array will be used. Calling reduce on an empty array without an initial value is an error. - developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Aug 28, 2017 at 15:50
  • so the second parameter passed to a reduce function is default, yes I understand that. But how does the callback function assume that distinct is that default parameter and not color? Commented Aug 28, 2017 at 15:52
  • 1
    The first parameter of the callback is always the default value - it doesn't shift around. Commented Aug 28, 2017 at 15:53

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

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, []);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.