Reputation: 34053
The .reduce()
method below, taken from this SO answer contains many parameters (appearantly called destructuring objects).
What functionality do these parameters represent?
let {result} = array.reduce(({arg_1, arg_2, arg_3}, arg_4)=> {
}, {result: [], arg_2: 0, arg_3: undefined})
return result
Upvotes: 0
Views: 111
Reputation: 13431
In case OP stumbles over the destructuring notation, for the given example, the first parameter is the initial value (described with the provided links of the first two comments), working as a collector or accumulator object. It is made up of the first three arguments of another method. The result is written by a destructuring assignment, thus, there will be 3 variables, arg_1
, arg_2
and arg_3
derived from the equally named arguments of the finally returned collector object.
edit, for the OP's provided example code has changed ...
The next example takes the OP's linked SO code reference into account ...
let {slots} = array.reduce(({slots, count, prev}, item)=> {
// ... do something with slots
// ...
// while iterating always needs to return
// an equally structured collector object
return {slots, count: count + 1, prev: item}
}, {slots: [], count: 0, prev: undefined})
/*
return slots; // does not really make sense within this shortened example's context.
*/
... is equal to ...
var slots = array.reduce(function (collector, item) {
var
slots = collector.slots,
count = collector.count,
prev = collector.prev;
// ... do something with slots
// ...
// while iterating always needs to return
// an equally structured collector object
return {slots: slots, count: count + 1, prev: item};
}, {slots: [], count: 0, prev: undefined}).slots;
Upvotes: 2
Reputation: 85575
The reduce method accepts two arguments.
Syntax:
arr.reduce(callback[, initialValue])
So, in your example the callback is used as first argument is arrow function. Let's break it:
1. ({arg_1, arg_2, arg_3}, arg_4)=> {} //the callback
2. {arg_1: [], arg_2: 0, arg_3: undefined} // the initial value
And ({arg_1, arg_2, arg_3}, arg_4)
has two arguments for arrow function, first is declared as object.
You can notice that the initial value for arg_4
is missing.
Upvotes: 2
Reputation: 24945
Array.reduce takes 2 parameters,
Array.reduce's callback gets 4 parameters:
Value of previousValue
is initialValue
at the start of loop. If no value is passed, first element is taken as previousValue
and currentValue
will have next value. From them, previousValue
will hold the value returned in previous iteration.
var a = [1,2,4,4,5,6,7,8];
a.reduce(function(p,c,i,a){
console.log(p,c,i,a);
return c
})
var a = [1,2,4,4,5,6,7,8];
a.reduce(function(p,c,i,a){
console.log(p,c,i,a);
return c
},0)
Upvotes: 1