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?
Thank you.
while(fruits)
, which will run for as long as fruits evaluates to true, instead of just going through the array once. – yahelc Nov 29 '10 at 21:34