Remove Every Other Array Element in JavaScript
- 1 minute read
Consider the following array:
let array = [`good`, `bad`, `good`, `bad`];
Let’s imagine we wanted to remove every other element from this array. Here’s a snippet that will do just that, thanks to splicing:
let i = array.length;
while (i--) (i + 1) % 2 === 0 && (array.splice(i, 1));
After the above snippet has executed, array
will equal ["good", "good"]
, as expected.
If you needed to, you could alternatively start counting earlier and begin by removing the first element:
let i = array.length;
while (i--) i % 2 === 0 && (array.splice(i, 1));
Once the above snippet has executed, array
will equal ["bad", "bad"]
.
Remove every nth array element
We can also apply this strategy in a similar way to remove every nth element from an array:
let i = array.length;
let n = 5; // The "nth" element to remove
while (i--) (i + 1) % n === 0 && (array.splice(i, 1));
The above snippet will remove every fifth element from array
, but you can substitute any other natural number for n
.
Conclusion
There’s lots of handy little tricks for manipulating JavaScript arrays that I have saved, including this one. They certainly come in handy!
Thanks for reading.