gpt4 book ai didi

javascript - lodash - 将两个数组分组/求和成对象

转载 作者:行者123 更新时间:2023-11-28 15:12:50 29 4
gpt4 key购买 nike

我有两个数组(一个键和一个值),我想将它们分组到一个对象中,并在键相同时对值求和。

var keys = ['a', 'b', 'a', 'c'];
var values = [1, 2, 2, 3];

我尝试使用 lodash zibObject() 但无法使用此函数对值求和。我想使用 zipWith() 会是解决方案,但我不知道如何求和。

var grouped = _.zipWith(keys, values, function(a,b){
return {a: b}; // not summing: [{a: 1}, {b: 2}, {a, 2}, {c: 3}]
});

但我想要的是:

var result = {
a: 3,
b: 2,
c: 3
};

使用 lodash 实现这一目标的正确方法是什么?

最佳答案

没有破折号或下划线

var keys = ['a', 'b', 'a', 'c'];
var values = [1, 2, 2, 3];
var grouped = {};

if (keys.length !== values.length) throw "array don't match!!"
for (var i = 0, len = keys.length; i < len; i++) {
grouped[keys[i]] = grouped[keys[i]] + values[i] || values[i];
}
document.getElementById('final').innerHTML = JSON.stringify(grouped);
<pre id="final"></pre>

关于javascript - lodash - 将两个数组分组/求和成对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35486540/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com