How to remove every second and third element from an array?

I want to remove every second and third element from an array in Javascript.

My array looks like this:

var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10"]; 

Now I want to remove every second and third element. The result will look like this:

 ["Banana", "Orange", "Apple"] 

I tried using a for loop and splice:

 for (var i = 0; fruits.length; i = i+3) { fruits.splice(i+1,0); fruits.splice(i+2,0); }; 

Of course, this returns an empty array, because the elements are deleted while the loop is still running.

How can I do it right?

+7
javascript arrays splice
source share
6 answers

You can approach this from a different angle and push() value that you do not want to delete in another array:

 var firstFruits = [] for (var i = 0; i < fruits.length; i = i+3) { firstFruits.push(fruits[i]); }; 

This approach may not be as brief as using splice() , but I think you see a gain in terms of readability.

+14
source share

This works for me.

 var fruits = ["Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10","Pear","something","else"]; for(var i = 0; i < fruits.length; i++) { fruits.splice(i+1,2); } //fruits = Banana,Orange,Apple,Pear 

Here is a demo that illustrates this a bit better: http://jsfiddle.net/RaRR7/

+9
source share

You can use a filter:

 var filtered = [ "Banana", "yellow", "23", "Orange", "orange", "12", "Apple", "green", "10" ].filter(function(_, i) { return i % 3 === 0; }) 

Return:

 ["Banana", "Orange", "Apple"] 
+2
source share

Try looping through an array in reverse order

+1
source share

Have you just considered copying the first, fourth, and seventh elements into a new array? This is not a very efficient memory, but it will still work fine.

0
source share

You will want to move back through the array, and then if i % 2 == 0 || i%3 == 0 i % 2 == 0 || i%3 == 0 , then splicing the element from the array

0
source share

All Articles