With reduce function this was supposed to return 9000 but how come does it return 256000? I tested similar code before and it worked fine
function combined(...s) {
return s.flat().reduce(x => x x)
}
console.log(combined([1000, 1000, 1000], [1000, 1000, 1000], [1000, 1000, 1000]))
CodePudding user response:
reduce
normally takes 2 parameters, in your case x
holds the accumulated value, and the second parameter, y
that I added, would be the current value in the iteration. You would have to use it like this:
function combined(...s){
return s.flat().reduce((x, y) => x y)
}
console.log(combined([1000,1000,1000],[1000,1000,1000],[1000,1000,1000]))
CodePudding user response:
Array.reduce()
callback function requires 2 parameters at least: accumulator
and currentValue
.
Also, you can pass an initial value to the accumulator
, which in this case should be 0
function combined(...s){
return s.flat().reduce((result, x) => result x, 0)
}
console.log(combined([1000,1000,1000],[1000,1000,1000],[1000,1000,1000]))
In your case, the x
stands for the accumulator
which initialized with the first element of the array: 1000
, and you are basically returning accumulator accumulator
, which results in the following:
- 2000 (1000 1000)
- 4000 (2000 2000)
- 8000 (4000 4000)
...
- 256000 (128000 128000)