0

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.

2 Answers 2

3

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

1 Comment

That resolved it - I ended up going down a slightly different route of reconstructing the array by looping through selected elements which seems to work much better. But this resolved the question. Accepted. Thanks!
0

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?

1 Comment

Yeah - logging it out is 9,3,6 100%

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.