我想返回一个由要排序的字典数组中的数组组成的新数组。我可能没有正确解释,但我只会举例说明我正在尝试做的事情。
所以我有以下内容:
let foo = [{"id": "hello123"}, {"id":"goodbye123"}, {"id":"hello123"}];
我想按 id 值对其进行排序并返回一个数组字典的数组,如下所示:
let bar = sortByKey(foo, "id");
console.log(bar);
output = [[{"id":"hello123"},{"id":"hello123"}],[{"id":"goodbye123"}]]
到目前为止,我只知道如何对待办事项进行排序,以便结果如下:
[{"id":"hello123"},{"id":"hello123"},{"id":"goodbye123"}]
最佳答案
您可以对组和 Array#reduce
使用哈希表用于迭代数组并将所有对象分配给它们的组。
稍后返回哈希表中的所有值。
function groupBy(array, group) {
return Object.values(array.reduce((hash, o) => {
hash[o[group]] = hash[o[group]] || [];
hash[o[group]].push(o);
return hash;
}, Object.create(null)));
}
var data = [{ id: "hello123" }, { id: "goodbye123" }, { id: "hello123" }];
console.log(groupBy(data, "id"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
与 Map
相同并且稍微短一些。
function groupBy(array, group) {
return Array.from(array
.reduce((m, o) => m.set(o[group], [...(m.get(o[group]) || []), o]), new Map)
.values()
);
}
var data = [{ id: "hello123" }, { id: "goodbye123" }, { id: "hello123" }];
console.log(groupBy(data, "id"));
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 按字典值排序后如何返回字典数组的新数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55917049/