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)
Your splicing code has only one error, which has been picked up in the comments (It should be: beasts.indexOf("bison") + 1 and not beasts.indexOf("bison"+1)
as @adiga says).
My guess is, however, that you'd actually like to remove all instances of 'bison'
from the list. I may be wrong there, but it's a guess. You can do that with a filter:
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];
const updatedBeasts = beasts.filter(beast => beast !== 'bison');
console.dir(updatedBeasts);
The problem is you are going for bison+1
not bison
so try this:
var beasts = ['ant', 'bison', 'camel', 'duck', 'bison', 'duck', 'duck', 'bison', "duck", 'bison',"camel", "duck", "duck"];
beasts.splice(beasts.indexOf("bison",beasts.indexOf("bison")),1);
console.log(beasts);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With