1

I am using splice method to remove a subarray from an array with the following code:


    for(let i = 0; i < cid.length; i++)
    {
      if(coinsValue[cid[i][0]] < troco && cid[i][1] > 0)
          available += cid[i][1]
      if(coinsValue[cid[i][0]] > troco)
          cid[i].splice(0)
    }


The output is :

[ [ 'PENNY', 1.01 ],
  [ 'NICKEL', 2.05 ],
  [ 'DIME', 3.1 ],
  [ 'QUARTER', 4.25 ],
  [ 'ONE', 90 ],
  [ 'FIVE', 55 ],
  [ 'TEN', 20 ],
  [ 'TWENTY', 60 ],
  [] /// removed elements from this array, but not the array itself ]

As you can see the elements that fit the condition are removed and I'm still left with an empty array. However I want to remove it completely!

Any help?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
izzypt
  • 170
  • 2
  • 16

1 Answers1

1

You're removing items from a sub array, not from the array itself.

To remove item from the top array you should do like this:

cid.splice(i, 1) instead of cid[i].splice(0)

for(let i = 0; i < cid.length; i++) {
    if (coinsValue[cid[i][0]] < troco && cid[i][1] > 0) {
        available += cid[i][1];
    } else if (coinsValue[cid[i][0]] > troco) {
        cid.splice(i, 1);
    }
}