Search code examples
javascriptindexofsplice

How to remove the next element after the first?


The goal was to get every other element of an array that matches the condition I had, but I couldn't get to do that.

So, I set off to try on another example which is found in the Array.prototype.indexOf() at MDN.

var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];

beasts.splice(beasts.indexOf("bison",beasts.indexOf("bison"+1)),1);
console.log(beasts);

I'd expect it to remove the second "bison" from the array and yet it removes the last element which is "duck"...

What could I do here? (granted I might have not yet learned proper syntax for this stuff)


Solution

  • You need to fix your indexOf syntax

    beasts.indexOf("bison"+1)  // this searches for `bison1`
    

    to this

    beasts.indexOf("bison") + 1
    

    var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];
    
    beasts.splice(beasts.indexOf("bison",beasts.indexOf("bison")+1),1)
    console.log(beasts);