how do i remove every 3rd element from an array?
var TheArray = ['h', 'e', 'z', 'l', 'l', 'l', 'o']
How do I make this say "hello" without creating a new array?
how do i remove every 3rd element from an array?
var TheArray = ['h', 'e', 'z', 'l', 'l', 'l', 'o']
How do I make this say "hello" without creating a new array?
Share Improve this question edited Mar 20, 2013 at 20:14 Anthony Forloney 91.8k14 gold badges118 silver badges116 bronze badges asked Mar 20, 2013 at 20:13 CuriouslyCuriously 3613 silver badges10 bronze badges 2-
Just to let you know, creating a new array will be about 20 times faster in this case, i.e.
newArray = []; for (i = 0; i <= TheArray.length; i += 3) newArray.push(TheArray[i]) && newArray.push(TheArray[i+1]);
– Andrej Burcev Commented Jun 22, 2017 at 13:59 - jsfiddle: jsfiddle/yexqr68z/1 – Andrej Burcev Commented Jun 22, 2017 at 14:14
4 Answers
Reset to default 10Try this:
for (var i = 2; i <= TheArray.length; i += 2)
TheArray.splice(i, 1);
If you want a string in the end, just use TheArray.join("")
.
Another way to do this is to use the Array.prototype.filter() function. Here is how to remove every 3rd element using it:
var TheArray = ['h', 'e', 'z', 'l', 'l', 'l', 'o']
TheArray = TheArray.filter(function(d, i){ return (i+1)%3 !== 0; })
Hope it helps.
If you want a string, don't change the array.
var r = '';
for (var i=0; i<TheArray.length; i++) {
if (i%3!=2) r += TheArray[i];
}
// now r is "hello"
Try this one:
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']