所以,我有两个分离的数组,它们始终具有相同数量的项目,看起来像这样:
array1 = ["Chicken","Chicken","Beef","Shrimp","Beef","Chicken"]
array2 = [2,3,4,1,3,2]
我该如何对所有相应项目的值求和:
Chicken: 7
Beef: 7
Shrimp: 1
欢呼
答案 0 :(得分:2)
您可以尝试
let array1 =["Chicken","Chicken","Beef","Shrimp","Beef","Chicken"]
let array2 = [2,3,4,1,3,2]
let op = array1.reduce((output,current,index)=>{
if(output[current]){
output[current] +=array2[index];
} else {
output[current] = array2[index];
}
return output;
},{})
console.log(op);
答案 1 :(得分:1)
您可以使用.map()
和.reduce()
方法来获取结果对象:
let array1 = ["Chicken", "Chicken", "Beef", "Shrimp", "Beef", "Chicken"];
let array2 = [2, 3, 4, 1, 3, 2];
let result = array1.map((v, i) => [v, array2[i]])
.reduce((r, [k, v]) => (r[k] = (r[k] || 0) + v, r), {});
console.log(result);
参考:
答案 2 :(得分:1)
您可以使用单 Array.reduce
来做到这一点:
@Configuration
@ComponentScan({"abc.department.common.configs.mongo","abc.department.common.configs.security.web"})
public class MyServiceConfigs {
}
或细分且更具可读性的格式:
const keys = ["Chicken","Chicken","Beef","Shrimp","Beef","Chicken"]
const vals = [2,3,4,1,3,2]
console.log(keys.reduce((r,c,i) =>
(r[keys[i]] = (r[keys[i]] || 0) + vals[i], r), {}))