如何在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
- Loop through each element in
arr1, keeping track of its index. - 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 witharr1[i+1] - 1. - If it’s the last element (323), end with 325 as specified.
- If it’s not the last element in
- Generate a subarray containing every integer from start to end (inclusive).
- 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
相关产品推荐
相关产品推荐

