将列表的javascript列表减少为列表字典[关闭]
Posted
技术标签:
【中文标题】将列表的javascript列表减少为列表字典[关闭]【英文标题】:Reduce javascript list of lists to a dictionary of lists [closed] 【发布时间】: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]
【问题讨论】:
请将您尝试的代码添加为minimal reproducible example。 【参考方案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 个步骤中的每一个提供了注释。
文档链接:
Array destructuring
Array.prototype.reduce
Array.prototype.push
??=
The logical nullish assignment operator
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 ... 关于上述方法还有什么问题吗?以上是关于将列表的javascript列表减少为列表字典[关闭]的主要内容,如果未能解决你的问题,请参考以下文章