javascript - JS 按具有两个不同数组和总和值的组对数组值进行分组
问题描述
我有两个数组
array1 =['0-18''18-19','18-19','18-19','20-22']
每个 array1 在第二个数组中都有值
array2=['100','200','300','400','500']
我想要像这样的输出
array1 =['0-18''18-19','20-22']
array2=['100','900','500']
请帮助填充这两个数组。在 Javascript 中
解决方案
您可以做的一件事是循环array1
并添加元素作为对象中的键。对象键是唯一的,因此这将消除重复项。当你这样做时,你可以从array2
.
let array1 =['0-18','18-19','18-19','18-19','20-22']
let array2=['100','200','300','400','500']
let sums = array1.reduce((obj, key, index) => {
if (!obj.hasOwnProperty(key)) obj[key] = 0 // if we haven't added the key, do it and set it to zero
obj[key] += Number(array2[index]) // now add the amount from array2
return obj
}, {})
console.log(Object.keys(sums)) // the unique keys will be in the keys of the object
console.log(Object.values(sums)) // the sums will be in the values
推荐阅读
- amazon-web-services - AWS Auto Scaling 终止实例并使用新的根卷和 IP 创建第二个实例。自动缩放在这里有什么用?
- node.js - map函数后获取数据
- html - html css 分页符
- excel - 如何在两个给定的编号之间生成列表。在excel中
- c# - Elastic Search Nest - 比较两个字段
- javascript - 无法在本机反应的视图之间导航
- angular - RxJS Observables - 多个订阅者获取对同一个对象的引用
- angular - 带树的角形材料表
- pyspark - pyspark - 将一次热编码后获得的稀疏向量转换为列
- javascript - FileSaver.js Chrome 问题,多个文档