Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Howto delete every second and third element from an array?

I want to delete 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 delete every second and third element. The result would look like this:

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

I tried to use 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 removed while the loop is still executed.

How can I do this correctly?

like image 593
Bob Avatar asked Nov 29 '10 21:11

Bob


2 Answers

You could approach this from a different angle and push() the value you don't want deleted into another Array:

var firstFruits = []

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

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

like image 68
McStretch Avatar answered Sep 21 '22 15:09

McStretch


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's a demo that illustrates it a little better: http://jsfiddle.net/RaRR7/

like image 23
Robert Avatar answered Sep 23 '22 15:09

Robert