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?

2
  • 1
    What is your example input data, and what's your expected output? Commented Sep 22, 2021 at 18:13
  • it seems like you should use cid.splice(i, 1); cid[i].splice(0) delete all elements of subarray Commented Sep 22, 2021 at 18:13

1 Answer 1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.