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)??
,[]- the second parameter you pass toreduceis the type ofdistinct- 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/…distinctis that default parameter and notcolor?