Reputation: 23
I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element.
var a = [];
a.push("cs");
a.push("ac");
var curr2 = a.indexOf("ac");
if(curr2 != -1){
a = a.splice(curr2,1);
}
console.log(a);
Expected result : ["cs"] Actual Result : ["ac"]
Can someone explain this behaviour. Thanks!
Upvotes: 0
Views: 343
Reputation: 395
splice
returns the item you have deleted in a array. In short, change a = a.splice(curr2,1);
to a.splice(curr2,1);
and your code will work as expected. Since splice
modifies the array you will get an array without the desired element. Where as before you were reassigning a to the return value of splice
Upvotes: 0
Reputation: 141
That's because Splice return the elements that you removed.
Remember that Splice modifies the original Array so when you make
a = a.splice(curr2,1);
You are storing the elements removed.
Replace that line with
a.splice(curr2,1);
And that should solve your problem!
Upvotes: 3
Reputation: 6923
You code is pulling 1 element from the array starting at index 1:
var a = [];
a.push("cs");
a.push("ac");
var curr2 = a.indexOf("ac");
console.log("curr2 = " + curr2);
// curr2 = 1;
if (curr2 != -1) {
var b = a.slice();
b.splice(curr2, 1);
console.log(b);
// ["ac"]
var c = a.slice();
c.splice(1, 1);
console.log(c);
// ["ac"]
}
Upvotes: 0