user1184100
user1184100

Reputation: 6894

Issues with javascript splice

I have a small piece of code in which i'm trying to splice an item from an array. In below code it should remove item which has "Javascript" and the resulting array should contain only "Java". What am i doing wrong here ?

var autoCompleteArray = new Array();

var item = new Array();
item.push("1");
item.push("Java");
autoCompleteArray.push(item);

var item2 = new Array();
item2.push("2");
item2.push("Javascript");
autoCompleteArray.push(item2);


var val = "Javascript";

for(var i=0;i<autoCompleteArray.length;i++){

  if(autoCompleteArray[i][1] == val) {

    autoCompleteArray.splice(autoCompleteArray[i],1);

  }
}

console.log(autoCompleteArray);  //Should show Java in the array since Javascript item has been removed.

Upvotes: 2

Views: 1919

Answers (2)

Aadit M Shah
Aadit M Shah

Reputation: 74204

As @Jack mentioned you need to pass an index (not a value) to splice. I would rewrite your loop as:

for (var i = 0; i < autoCompleteArray.length; i++) {
    if (autoCompleteArray[i][1] === val) {
        autoCompleteArray.splice(i--, 1);
    }
}

That should solve your problem. See the demo here: http://jsfiddle.net/7PM94/

Also note that you can create arrays using the literal syntax instead of pushing elements. You can define autoCompleteArray as follows:

var autoCompleteArray = [
    ["1", "Java"],
    ["2", "JavaScript"]
];

Hope that helps.

Upvotes: 1

Ja͢ck
Ja͢ck

Reputation: 173542

You're splicing the wrong thing; this should work:

  if(autoCompleteArray[i][1] == val) {
    autoCompleteArray.splice(i,1);
  }

The first argument to .splice() is the index, not the value at that index.

Be aware that when you splice at index i, for that iteration you should not increase i:

var i = 0;
while (i < autoCompleteArray.length) {
  if(autoCompleteArray[i][1] == val) {
    autoCompleteArray.splice(i, 1);
    continue;
  }
  ++i;
}

This is fine if there can be only one match of course, in which case you can also break; out of the loop.

Upvotes: 2

Related Questions