将 javascript 个列表列表缩减为列表字典

Reduce javascript list of lists to a dictionary of lists

类似于List of Lists to Dictionary of Lists

想要将列表列表缩减为列表字典 例如

list_list = [['example', 55], ['example', 66] , ['example2', 44]]

会变成

dict = {'example': [55,66], 'example2': [44]}

好像自己动手了,所以才来回答

Array.reduce 和数组解构将帮助你。

逻辑请看代码注释

const list_list = [['example', 55], ['example', 66] , ['example2', 44]];
//Destructuring the current value in the reduce function into [key, value]
const dict = list_list.reduce((acc, [key, value]) => {
  // If a node with the current key exist in the accumulator, merge the value of that node with current value
  // If node with current key doesnot exist, create a new node with that key and value as an array with current value being the element
  acc[key] = acc[key] ? [...acc[key], value] : [value];
  return acc;
}, {});
console.log(dict);

这是如何实现 reducer 功能的另一种变体。它试图提高可读性,并且还为每个 reduce 周期必须执行的 3 个步骤中的每一个添加注释。

文档链接:

const list_list = [['example', 55], ['example', 66] , ['example2', 44]];

console.log(
  list_list

  //.reduce((result, item) => {
  //  // array destructuring of the currently processed array item.
  //  const [key, value] = item;

    // array destructuring within the reducer function's head.
    .reduce((result, [key, value]) => {

      // create and/or access the property list
      // identified by the array item's `key`.
      const groupList = (result[key] ??= []);

      // push the array item's `value`
      // into the above accessed list.
      groupList.push(value);

      // return the mutated `result` ... (the
      // stepwise aggregated final return value).
      return result;

    }, {}) // pass the final result's initial state as 2nd argument.
)