javascript - 按字典值排序后如何返回字典数组的新数组

标签 javascript arrays sorting dictionary

我想返回一个由要排序的字典数组中的数组组成的新数组。我可能没有正确解释,但我只会举例说明我正在尝试做的事情。

所以我有以下内容:

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/

相关文章:

Python:使用另一个列表顺序对列表进行排序,具有不同的长度,并且没有 'sorted'

javascript - Angular JS : Javascript not working inside custom directive template

javascript - 在图像上拖动一个矩形

php - 将复选框数组分配给变量

python - 如何检查一个数字是否已经在二维 numpy 数组的第一列中

c# - ListView 排序未设置 SortExpression 和 SortDirection

javascript - 是否可以在 768px 分辨率以下添加 <a> 元素?

javascript - YouTube API,定义为类(class)并停止播放视频

c++ - 在 Visual C++ 中打印数组

node.js - 如何使用apollo服务器对graphQl中的数据进行排序?