最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript how to remove every 3rd element from an array - Stack Overflow

programmeradmin4浏览0评论

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
Add a ment  | 

4 Answers 4

Reset to default 10

Try 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']
发布评论

评论列表(0)

  1. 暂无评论