Kolisetty Raghavendra
Kolisetty Raghavendra

Reputation: 23

Splice() function not working as expected

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

Answers (3)

Djtouchette
Djtouchette

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

Eduardo González
Eduardo González

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

Alexander Higgins
Alexander Higgins

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

Related Questions