如何按指定数组顺序分组嵌套数组元素并合并对应值?
Solution for Grouping and Merging Nested Arrays by Specified Order
Hey there! Let's work through this problem step by step—we need to group the nested arrays by the exact order defined in ind, then merge their corresponding numeric values column-wise. Here's how to make it happen:
Step 1: Lay Out the Original Data
First, let's recap your input arrays for clarity:
const ind = ["Apple", "Pear", "Banana"]; const arr = [ [ "Pear", 12, 34, 54, 76, 23, 232 ], [ "Apple", 54, 22, 11, 23, 21, 33 ], [ "Banana", 54, 65, 11, 43, 66, 75 ], [ "Pear", 23, 11, 46, 76, 33, 98 ], [ "Apple", 12, 34, 54, 76, 23, 232 ], [ "Banana", 54, 22, 11, 23, 21, 33 ], ];
Step 2: Implement the Solution Code
Here's the code that will transform your input into the desired output:
// 1. First, group all value arrays by their fruit name const fruitGroups = arr.reduce((acc, currentItem) => { const fruitName = currentItem[0]; const numericValues = currentItem.slice(1); // Grab all values after the fruit name if (!acc[fruitName]) { acc[fruitName] = []; } acc[fruitName].push(numericValues); return acc; }, {}); // 2. Build the final result following the order in `ind` const finalResult = ind.map(fruit => { const allValueArrays = fruitGroups[fruit]; // Merge values column-wise: collect the nth value from each array const mergedColumns = allValueArrays[0].map((_, index) => { return allValueArrays.map(valueArr => valueArr[index]); }); // Combine fruit name with merged columns return [fruit, ...mergedColumns]; }); console.log(finalResult);
Step 3: Check the Output
When you run this code, you'll get exactly the structure you want (note: I spotted a small typo in your expected result for Pear's last value—it should be [232, 98] instead of [232, 38], since the original Pear subarrays end with 232 and 98):
[ ["Apple", [54,12], [22,34], [11,54], [23,76], [21,23], [33,232]], ["Pear", [12,23], [34,11], [54,46], [76,76], [23,33], [232,98]], ["Banana", [54,54], [65,22], [11,11], [43,23], [66,21], [75,33]] ]
Quick Breakdown of How It Works
- Grouping with
reduce: We loop througharrand build an object where each key is a fruit name, and the value is an array of all numeric value lists for that fruit. This makes it easy to fetch all values for a specific fruit later. - Mapping with
ind: We iterate over theindarray to guarantee our final result follows the exact order you specified. For each fruit, we usemapto create merged columns—for every index position, we pull the value from each of the fruit's value arrays and combine them into a subarray. - Assembling the Result: We attach the merged column subarrays to the fruit name to form each entry in our final array.
内容的提问来源于stack exchange,提问作者leyar.themes
相关产品推荐
相关产品推荐

