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.
If it’s inconsistent, sometimes the parameter
indexis a string, and sometimes it’s a number.$.inArray('3', arr)will return-1.$.inArray(3, arr)will return1.See splice’s docs.
You can make sure it’s always a number by doing this:
… or …