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

如何在JavaScript中基于旧数组生成由起始值和终止值确定的二维数组

Solution to Generate Your Custom 2D Array

The issue with using a generic chunk_array method is that it’s designed for splitting arrays into fixed-size chunks, but your requirement calls for variable-length subarrays based on the next element in arr1. Here’s a straightforward approach to build newArr exactly as you need:

Step-by-Step Approach

  1. Loop through each element in arr1, keeping track of its index.
  2. For each element:
    • Use the current element as the start of your subarray.
    • Calculate the end of the subarray:
      • If it’s not the last element in arr1, end with arr1[i+1] - 1.
      • If it’s the last element (323), end with 325 as specified.
    • Generate a subarray containing every integer from start to end (inclusive).
  3. Collect all these subarrays into newArr.

Example Code (JavaScript)

Here’s a concise implementation using map and Array.from for cleaner code:

const arr1 = [4, 26, 40, 53, 58, 68, 73, 86, 91, 114, 119, 132, 137, 147, 152, 165, 170, 183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289, 301, 306, 318, 323];

const newArr = arr1.map((start, index) => {
  // Determine the end value for each subarray
  const end = index === arr1.length - 1 ? 325 : arr1[index + 1] - 1;
  // Generate the range from start to end
  return Array.from({ length: end - start + 1 }, (_, i) => start + i);
});

// Verify the result
console.log(newArr);

Alternative (More Explicit Loop)

If you prefer a more verbose approach for clarity:

const arr1 = [4, 26, 40, 53, 58, 68, 73, 86, 91, 114, 119, 132, 137, 147, 152, 165, 170, 183, 188, 201, 206, 208, 215, 220, 233, 238, 250, 255, 267, 272, 284, 289, 301, 306, 318, 323];
const newArr = [];

for (let i = 0; i < arr1.length; i++) {
  const start = arr1[i];
  let end;
  
  // Set end based on whether it's the last element
  if (i === arr1.length - 1) {
    end = 325;
  } else {
    end = arr1[i + 1] - 1;
  }
  
  // Build the subarray
  const subArray = [];
  for (let num = start; num <= end; num++) {
    subArray.push(num);
  }
  
  newArr.push(subArray);
}

console.log(newArr);

Both implementations will produce the exact 2D array you described. The key is that we’re dynamically calculating each subarray’s length based on the next element in arr1, which a generic chunking method can’t handle out of the box.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 16:52:50