Cash register some questions

else {
    var reverse = cid.reverse()
    var arr = reverse.slice()
    for (let i = 0; i < arr.length; i++) {
      arr[i][1] = 0
    }
    console.log(reverse)

When I console log reverse every value is set to “0” which is only what I wanted for the var “arr”. Why is reverse getting mutated even though I used slice?

I’m guessing that something else is going on with the rest of your code. slice does not mutate the array. Here is the code you shared in isolation:

This is what I get

var reverse = cid.reverse()
    var arr = reverse.slice()
    console.log(reverse) 
    for (let i = 0; i < arr.length; i++) {
      arr[i][1] = 0
    }
    console.log(reverse)

First console log returns //[ [ ‘ONE HUNDRED’, 100 ],
[ ‘TWENTY’, 60 ],
[ ‘TEN’, 20 ],
[ ‘FIVE’, 55 ],
[ ‘ONE’, 90 ],
[ ‘QUARTER’, 4.25 ],
[ ‘DIME’, 3.1 ],
[ ‘NICKEL’, 2.05 ],
[ ‘PENNY’, 1.01 ] ]

Second one returns // [ [ ‘ONE HUNDRED’, 0 ],
[ ‘TWENTY’, 0 ],
[ ‘TEN’, 0 ],
[ ‘FIVE’, 0 ],
[ ‘ONE’, 0 ],
[ ‘QUARTER’, 0 ],
[ ‘DIME’, 0 ],
[ ‘NICKEL’, 0 ],
[ ‘PENNY’, 0 ] ]

Ah. What you’re seeing isn’t because of slice. It’s because the array contains arrays. arr is a copy of reverse, but it contains references to the same array objects.

So how do I fix this??

I tried the spread operator but it didnt work. I found JSON.parse(JSON.stringify(reverse) works

It looks like the only thing that you want from the original array is the names (since you’ll be setting all the values to 0 anyway. Instead of copying the array and then iterating over it to set the values to 0, why not just use the for loop to construct the new array? You can skip the copying altogether.

1 Like

Also, just to be clear, reverse mutates the original array (just an FYI).

2 Likes
for (let i = 0; i < arr.length; i++) {
    if (arr[i][1] === 0) {
      delete arr[i]
    }
  }
  console.log(arr)

returns

[ ,
  [ 'TWENTY', 60 ],
  [ 'TEN', 20 ],
  [ 'FIVE', 15 ],
  [ 'ONE', 1 ],
  [ 'QUARTER', 0.5 ],
  [ 'DIME', 0.2 ],
  ,
  [ 'PENNY', 0.04 ] ]

Is there a way to remove nested arrays without leaving the empty space? Or how do I get rid of the empty space now?

Hi!
I am also new to this stuff, so better check twice.

I would rather use the filter function on that array.
Or maybe create my own kind of filter function, where I would create a new array from your old one, but only with values, which passed a test.
In your case the test would be: arr[i][1] !== 0.

Will it work?

Ya arr.filter(Boolean) works.