首页 > 解决方案 > 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 中

标签: 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


推荐阅读