kieran
kieran

Reputation: 2312

Removing item from array by value in JavaScript giving unpredictable results

I have this code for removing an item from an array by value in JS...

function remove_item(index){

    //log out selected array
    console.log('before >> ' + selected); //

    //log out item that has been requested to be removed
    console.log('removing >> ' + index);

    //remove item from array
    selected.splice( $.inArray(index,selected) ,1 );

    //log out selected array (should be without the item that was removed
    console.log('after >> ' + selected);

    //reload graph
    initialize();
}

This is what my array looks like...

selected = [9, 3, 6]

If I call remove_item(3) this is what gets logged out...

before >> 9,3,6
removing >> 3
after >> 9,3

After should be 9,6 not 9,3

I'm totally stumped on this as it sometimes works and sometimes doesn't...

For example I just tried remove_item(10) and this worked...

before >> 1,2,10
removing >> 10
after >> 1,2

I'm sure it has something to do with this line:

selected.splice( $.inArray(index,selected) ,1 );

Any help much appreciated.

Upvotes: 0

Views: 406

Answers (2)

wombleton
wombleton

Reputation: 8376

If it's inconsistent, sometimes the parameter index is a string, and sometimes it's a number.

$.inArray('3', arr) will return -1.

$.inArray(3, arr) will return 1.

[9, 3, 6].splice(-1, 1);  // removes last item from the array

See splice's docs.

You can make sure it's always a number by doing this:

//remove item from array
selected.splice( $.inArray(Number(index),selected) ,1 );

... or ...

function remove_item(index){
  index = Number(index);

Upvotes: 3

Bora
Bora

Reputation: 291

I tested your code and it works as intended.

I think you need to check your input array once more. Is it really [9,3,6] or do you expect it to be that?

Upvotes: 0

Related Questions