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

如何在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 accumulator starts 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.01 03:02:35