我想将一个数组排序为具有键值对的对象。
所以如果我有一个像这样的数组 [1,2,3,2,4,1,5,1,6] 它应该吐出这样的东西。我正在尝试使用 lodash!
{
1: [1, 1, 1],
2: [2, 2],
3: [3],
4: [4],
5: [5],
6: [6]
}
最佳答案
您可以使用 reduce()
并返回对象。
var ar = [1, 2, 3, 2, 4, 1, 5, 1, 6];
var result = ar.reduce(function(o, e) {
o[e] = (o[e] || []).concat(e);
return o;
}, {});
console.log(result)
关于javascript - 将数组排序为具有键和值对的对象,具有相同值的对象被插入相同的键/值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37971114/