Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why array is not iterable in reduce

I want to split array by even and odd elements, this is my code

A.reduce((a,v,i)=> v % 2 == 0 ? [...a[0],v] : [...a[1],v],[[],[]])

A is array of numbers. I don't understand why do I get an error

a[1] is not iterable?

Considering that this code is working ok:

let arr = [[],[]];
console.log([...arr[1], 4]);
like image 380
ogbofjnr Avatar asked Mar 25 '26 02:03

ogbofjnr


1 Answers

You are only returning a single array in reduce(). You also need to return the second. In the first iteration the a is [[],[]]. But after the first it will become only a single array.

let A = [1,2,3,4]
const res= A.reduce((a,v,i)=> v % 2 == 0 ? [a[0],[...a[1],v]] : [[...a[0],v],a[1]],[[],[]])
console.log(res)

You could use a trick here. As v % 2 will return 1 or 0 so you could push() to that and use , to return the original a without spread operator.

let A = [1,2,3,4]
const res= A.reduce((a,v,i)=> (a[v % 2].push(v),a),[[],[]])
console.log(res)
like image 184
Maheer Ali Avatar answered Mar 27 '26 15:03

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!