javascript – 如果另一个数组具有相同的元素,则连接数组元素

我有两个数组

var arrayA = ["a", "a", "b", "b", "a", "c"];
var arrayB = [10, 20, 3, 2, 20, 5];

如您所见,arrayA [0],arrayA [1],arrayA [4]具有相同的元素(arrayA [2],arrayA [3]也相同).

所以基于上面的例子,我想要arrayB [0],arrayB [1],arrayB [4]将被总结,而arrayB [2],arrayB [3]也是如此.

期望输出

arrayA = ["a", "b", "c"];
arrayB = [50, 5, 5];

如果arrayA具有基于arrayA索引的相同元素,则可以对arrayB元素求和吗?并且有一个Lodash / Underscore功能来做到这一点?

最佳答案
您可以使用索引的对象并维护值.

var arrayA = ["a", "a", "b", "b", "a", "c"],
    arrayB = [10, 20, 3, 2, 20, 5],
    indices = Object.create(null),
    groupedA = [],
    groupedB = [];
    
arrayA.forEach(function (a, i) {
    if (!(a in indices)) {
        groupedA.push(a);
        indices[a] = groupedB.push(0) - 1;
    }
    groupedB[indices[a]] += arrayB[i];
});

console.log(groupedA);
console.log(groupedB);
.as-console-wrapper { max-height: 100% !important; top: 0; }

改变原始数组的版本.

var arrayA = ["a", "a", "b", "b", "a", "c"],
    arrayB = [10, 20, 3, 2, 20, 5],
    indices = Object.create(null),
    i = 0;

while (i < arrayA.length) {
    if (!(arrayA[i] in indices)) {
        indices[arrayA[i]] = i++;
        continue;
    }
    arrayB[indices[arrayA[i]]] += arrayB.splice(i, 1)[0];
    arrayA.splice(i, 1);
}

console.log(arrayA);
console.log(arrayB);
.as-console-wrapper { max-height: 100% !important; top: 0; }

转载注明原文:javascript – 如果另一个数组具有相同的元素,则连接数组元素 - 代码日志