如何在JavaScript中将列表列表归约为列表字典?
How to Convert a List of Lists into a Dictionary of Lists in JavaScript
Hey there! This is a super common use case, and JavaScript's Array.prototype.reduce() method is perfect for this job—it’s built exactly for reducing an array into a single value (in this case, our target dictionary object).
Let’s walk through how to solve this with your example:
Input
const listList = [['example', 55], ['example', 66], ['example2', 44]];
Desired Output
{ example: [55, 66], example2: [44] }
Solution Code
Here’s a straightforward implementation using reduce:
const listList = [['example', 55], ['example', 66], ['example2', 44]]; const resultDict = listList.reduce((accumulator, [key, value]) => { // Initialize an empty array for the key if it doesn't exist yet if (!accumulator[key]) { accumulator[key] = []; } // Add the current value to the key's array accumulator[key].push(value); // Return the updated accumulator for the next iteration return accumulator; }, {}); // Start with an empty object as the initial accumulator console.log(resultDict); // Output: { example: [55, 66], example2: [44] }
Simplified Version
You can shorten the initialization step using a logical OR (||) to make the code more concise:
const resultDict = listList.reduce((acc, [key, value]) => { acc[key] = acc[key] || []; acc[key].push(value); return acc; }, {});
How It Works
reduce()iterates over each sub-array in your input list.- We use array destructuring (
[key, value]) to cleanly pull out the key and value from each sub-array. - The
accumulatorstarts as an empty object, and we build it up by adding each value to the corresponding key’s array. - If the key doesn’t exist in the accumulator yet, we create a new empty array for it before pushing the value.
This approach runs in O(n) time (where n is the number of sub-arrays) and is easy to follow once you’re familiar with how reduce works.
内容的提问来源于stack exchange,提问作者peewee6765
相关产品推荐
相关产品推荐

