Javascript how to remove every third element from an array

how to remove every third element from an array?

var TheArray = ['h', 'e', 'z', 'l', 'l', 'l', 'o']

How can I say hello without creating a new array?

+5
source share
3 answers

Try the following:

for (var i = 2; i <= TheArray.length; i += 2)
    TheArray.splice(i, 1);

If you need a line at the end, just use TheArray.join("").

+8
source

If you need a string, do not modify the array.

var r = '';
for (var i=0; i<TheArray.length; i++) {
   if (i%3!=2) r += TheArray[i];
}
// now r is "hello"
0
source

Try the following:

var arr = ['h', 'e', 'z', 'l', 'l', 'l', 'o'];
for(var i = 2; i < arr.length; i+=2)
    arr.splice(i, 1);
console.log(arr); // outputs ['h','e','l','l','o']
0
source

All Articles