Defining parameters in JavaScript reduces

I am considering this reduction 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 element of the array colors, it searches for a string colorin distinctand simply returns the array if it is found, and adds colorin distinctif not found.

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

Is JavaScript automatically assumed to be distinctan array because I am calling distinct.indexOf(color)??

+2
source share
2 answers

reduce() ( ), . MDN.

, . , :

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);
Hide result

() , , .

+2

MDN :

reduce() ( ), .

:

arr.reduce(callback[, initialValue]), (accumulator, currentValue) . , currentValue - , .

:

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

Source: https://habr.com/ru/post/1684623/


All Articles