【问题标题】:Reduce javascript list of lists to a dictionary of lists [closed]将列表的javascript列表减少为列表字典[关闭]
【发布时间】:2021-12-30 05:26:45
【问题描述】:

类似于List of Lists to Dictionary of Lists

希望将列表列表简化为列表字典 例如

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

会变成

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

【问题讨论】:

标签: javascript arrays reduce


【解决方案1】:

似乎已经动手了,所以才回答这个问题。

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);

【讨论】:

  • 感谢这个魅力!
【解决方案2】:

这里是如何实现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.
)

【讨论】:

  • @peewee6765 ... 关于上述方法还有什么问题吗?
猜你喜欢
  • 2021-03-03
  • 1970-01-01
  • 2016-03-15
  • 2015-07-27
  • 2014-05-16
  • 2016-02-18
  • 2021-03-31
  • 2021-03-03
  • 1970-01-01
相关资源
最近更新 更多