Ryan
Ryan

Reputation: 150

Can someone explain what is going on with `push` here?

It feels like push is behaving funny. Rather than just push to 1 index inside the forEach, it seems to be pushing to all 3 indexes. Am I missing something obvious?

 let arrayToReduce = [ [ 1, 2, 3 ] ]
    let reduced = arrayToReduce.reduce((arr, inner) => {
      const copied = arr.slice()
      inner.forEach((num, idx) => {
        copied[idx].push(num)
      })
      return copied
      }, Array(arrayToReduce[0].length).fill([]))

    console.log(reduced)

Expected output: [[1], [2], [3]]

Actual output: [[1, 2, 3], [1, 2, 3], [1, 2, 3]]

Upvotes: 0

Views: 52

Answers (2)

XMehdi01
XMehdi01

Reputation: 1

    let arr = [ [ 7, 3, 47 ] ]
    let reduced = arr.flat().map(e=>[e])
    console.log(reduced) 

//output: [[7], [3], [47]]

if you want your Expected output : [[1], [2], [3]]

Simply return index instead of item in inner array

    let arr = [ [ 7, 3, 47 ] ]
    let reduced = arr.flat().map((e,i)=>[i+1])
    console.log(reduced)

Upvotes: 0

Quentin
Quentin

Reputation: 943615

push isn't the culprit, it is fill.

You've created an array the same length as the original and then filled it with a value.

That value is an array.

The same array.

So when you push a value to copied[0] you get a reference to that array and put a value into it.

And when you push a value to copied[1] you get a reference to that same array and put another value into it.

Upvotes: 2

Related Questions