You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript数组中按间隔为特定类型元素插入新元素

How to Insert Elements into an Array Based on Element Type Counts (Avoiding forEach Iteration Issues)

Problem Statement

You have an initial array:

const initialArray = [ 
  { type: 'all' }, { type: 'all' }, { type: 'all' }, { type: 'fruit'}, 
  { type: 'all' }, { type: 'all' }, { type: 'fruit' }, { type: 'all' }, 
  { type: 'all' }, { type: 'fruit' }, { type: 'fruit' } 
];

Your requirements are:

  1. Insert {type: 'toys'} after every 5 elements with type: 'all'
  2. Insert {type: 'clothes'} after every 2 elements with type: 'fruit'

The expected result is:

[ 
  { type: 'all' }, { type: 'all' }, { type: 'all' }, { type: 'fruit'}, 
  { type: 'all' }, { type: 'all' }, { type: 'toys' }, { type: 'fruit' }, 
  { type: 'clothes' }, { type: 'all' }, { type: 'all' }, { type: 'fruit' }, 
  { type: 'fruit' }, { type: 'clothes' } 
];

When trying to use forEach directly on the original array, inserting elements modifies the array's length, which messes up the iteration (you end up processing new elements you just added, and lose track of the original elements). Your test code illustrates this issue:

array_demo.forEach((item, index) => { 
  array_demo.push({type: 'demo'}); 
  console.warn(index); 
});

Solution: Use a New Array to Collect Results

Instead of modifying the original array while iterating over it, create a new array to build your final result. Track counts of 'all' and 'fruit' elements as you iterate, and insert the required items into the new array when the counts hit your thresholds.

Here's the working code:

const initialArray = [ 
  { type: 'all' }, { type: 'all' }, { type: 'all' }, { type: 'fruit'}, 
  { type: 'all' }, { type: 'all' }, { type: 'fruit' }, { type: 'all' }, 
  { type: 'all' }, { type: 'fruit' }, { type: 'fruit' } 
];

const resultArray = [];
let allCount = 0;
let fruitCount = 0;

initialArray.forEach(item => {
  // Add the current item to the result first
  resultArray.push(item);

  // Update counters and check for insertion conditions
  if (item.type === 'all') {
    allCount++;
    // Insert 'toys' after every 5 'all' elements
    if (allCount === 5) {
      resultArray.push({ type: 'toys' });
      allCount = 0; // Reset counter after insertion
    }
  } else if (item.type === 'fruit') {
    fruitCount++;
    // Insert 'clothes' after every 2 'fruit' elements
    if (fruitCount === 2) {
      resultArray.push({ type: 'clothes' });
      fruitCount = 0; // Reset counter after insertion
    }
  }
});

console.log(resultArray); // This matches your expected output

Why This Works

  • We never modify the original initialArray during iteration, so forEach processes exactly the 11 elements you started with—no more, no less.
  • The counters (allCount and fruitCount) keep track of how many qualifying elements we've added to the result array so far. When we hit the threshold, we insert the required item and reset the counter to start tracking the next set.

内容的提问来源于stack exchange,提问作者Dicky Chan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:23:48