Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 383
Karolis Vaitkevicius Avatar asked Dec 17 '22 16:12

Karolis Vaitkevicius


2 Answers

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);
like image 61
OliverRadini Avatar answered Jan 04 '23 12:01

OliverRadini


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);
like image 29
AzmahQi Avatar answered Jan 04 '23 12:01

AzmahQi