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

JavaScript实现嵌套数组元素前移一位并插入首元素的方法

JavaScript实现嵌套数组的指定重组需求

Hey there! Let's break down how to solve this array transformation problem. The core idea is to flatten the nested array first, insert your target element at the start, then re-group the elements into subarrays of max 3 items each. Here's a clean, working solution:

Step-by-Step Solution Code

function rearrangeArray(originalNestedArr, insertElement) {
  // 1. Flatten the original nested array into a single-dimensional list
  const flattened = originalNestedArr.flat();
  // 2. Insert the new element at the beginning of the flattened list
  const combinedSequence = [insertElement, ...flattened];
  // 3. Split the combined list into subarrays with max 3 elements each
  const result = [];
  for (let idx = 0; idx < combinedSequence.length; idx += 3) {
    result.push(combinedSequence.slice(idx, idx + 3));
  }
  return result;
}

// Test with your sample data
const arr_1 = [1,2,3];
const arr_2 = [4,5,6];
const arr_3 = [7,8,9];
const arr = [arr_1, arr_2, arr_3];
const i = 0; // Replace this with any element you need to insert

console.log(rearrangeArray(arr, i));
// Output: [[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]

How It Works

  • Flattening the Array: We use Array.prototype.flat() to convert your nested array into a simple 1D array. This makes it way easier to manipulate the order of elements. For deeper nested arrays, you could pass a depth parameter (like flat(2)), but since your example only has one level of nesting, the default works perfectly.
  • Inserting the Element: Using ES6 spread operator (...), we quickly prepend your target element i to the flattened array, creating a new sequence that matches the order you need.
  • Re-grouping: We loop through the combined sequence in increments of 3, using slice() to grab chunks of up to 3 elements each and push them into the result array. This ensures no subarray ever has more than 3 elements, even if the total number of elements isn't a multiple of 3 (like the final [9] in your example).

Edge Cases Handled

This solution works for edge cases too:

  • If the original nested array is empty, you'll get [[insertElement]] as the result
  • If the flattened array plus the inserted element has fewer than 3 elements, it'll just return a single subarray with all elements
  • If you have deeper nested arrays (like [[[1,2],3],4]), just add a depth parameter to flat() (e.g., flat(Infinity) to flatten all levels)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:49:19