如何使用JavaScript的Reduce函数按键分组对象数组?
Absolutely! The reduce function is ideal for this grouping task—it lets you iterate through the array and build your desired result incrementally. Here's how to implement it:
const array = [ { 'red': 50 , 'green':99 , 'blue': 66}, {'blue':65, 'red': 88 }, { 'green':9 , 'blue': 6}, { 'red': 650 , 'green':959 , 'blue': 663} ]; const groupedResult = array.reduce((accumulator, currentObj) => { // Loop through each key-value pair in the current object for (const [color, value] of Object.entries(currentObj)) { // If the color key doesn't exist in the accumulator, initialize it as an empty array if (!accumulator[color]) { accumulator[color] = []; } // Push the value into the corresponding color array accumulator[color].push(value); } // Return the updated accumulator for the next iteration return accumulator; }, {}); // Start with an empty object as the initial accumulator console.log(groupedResult); // Output: { red: [50, 88, 650], green: [99,9,959], blue: [66,65, 6, 663] }
How this works:
- Initial Accumulator: We start with an empty object
{}—this will hold our final grouped result. - Iterate Over Array: For each object in the input array, we use
Object.entries()to get its key-value pairs (e.g.,['red', 50]for the first object). - Build Groups: For each color key:
- If the key isn't already in the accumulator, we create a new empty array for it.
- We then push the current value into that array.
- Update Accumulator: After processing all keys in the current object, we return the accumulator to continue building the result through subsequent iterations.
This approach handles objects with missing keys seamlessly—any color that appears in any object will get its own array with all corresponding values.
内容的提问来源于stack exchange,提问作者Nithya
相关产品推荐
相关产品推荐

