假设我在JavaScript中有两个长度相同的数组
Array_1 : ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'A', 'E']
Array_2 : ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2', '10']
现在如何将Array_1和Array_2分组在一起?
含义如下:
Array_1: ['A', 'B', 'C', 'D', 'E', 'F', 'G']
Array_2: ['8', '7', '8', '3', '18', '6', '9']
谢谢
答案 0 :(得分:1)
如果按组分组是指将具有相同键的值加在一起,则可以尝试:
let a = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'A', 'E'];
let b = ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2', '10'];
const temp = {};
a.forEach((value, index) => {
temp.hasOwnProperty(value) ? temp[value]+=parseInt(b[index]) : temp[value]=parseInt(b[index]);
});
a = Object.keys(temp);
b = Object.values(temp);
console.log(a, b);
答案 1 :(得分:0)
您可以使用reduce并以键值形式对数组进行分组。
let Array1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'A', 'E']
let Array2 = ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2', '10']
let op = Array1.reduce((op,inp,index)=>{
if(op[inp]){
op[inp] += Number(Array2[index])
} else {
op[inp] = Number(Array2[index])
}
return op
},{})
console.log(Object.keys(op))
console.log(Object.values(op))
答案 2 :(得分:0)
如果值已知,则可以迭代数组和拼接项,并更新array2
。
此提案使用数字而不是字符串,因为数字更易于添加。
它使用一个对象来跟踪索引。
var array1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'A', 'E'],
array2 = ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2', '10'].map(Number),
indices = {},
index = 0,
value;
while (index < array1.length) {
value = array1[index];
if (value in indices) {
array2[indices[value]] += array2[index];
array1.splice(index, 1);
array2.splice(index, 1);
continue;
}
indices[value] = index;
index++;
}
console.log(array1.join(' '));
console.log(array2.join(' '));
以Map
来缩短时间。
var array1 = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'A', 'F', 'C', 'A', 'E'],
array2 = ['5', '7', '4', '3', '8', '1', '9', '1', '5', '4', '2', '10'].map(Number),
map = array1.reduce((m, v, i) => m.set(v, (m.get(v) || 0) + array2[i]), new Map);
array1 = Array.from(map.keys());
array2 = Array.from(map.values(), String);
console.log(array1);
console.log(array2);