简体   繁体   中英

Reduce js - reduce to array

Can you tell me why that doesn't work and how to make it work, with a simple 'reduce' method?

let newArray = array.reduce((acc,value,index) => index%2 ? acc[0]+=value: acc[1]+=value ,[0,0]);
console.log(newArray);
Output: Nan

'array' is just an array with numbers.

Please don't create answers with some long and complex functions. I want to make it as simple as it can be.

I know that we can do this:

let sum = [0,0];

array.map((value,index)=> index%2? sum[0]+=value : sum[1]+=value);
console.log(sum);

but I'm just curious, why that doesn't work.

You aren't returning the accumulator ( acc ) from the function. You are returning the result of the assignment expression acc[0] += value which is just a number. On the next iteration you try to index into that number. You can fix this using something like:

 let array = [1, 2, 3, 4, 5] let newArray = array.reduce((acc,value,index) => (index % 2? acc[0] += value: acc[1] += value, acc),[0,0]) console.log(newArray);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM