gpt4 book ai didi

javascript - 删除数组中的重复值并合并与第二个数组关联的值

转载 作者:行者123 更新时间:2023-12-03 02:52:23 26 4
gpt4 key购买 nike

我有两个数组第一个是 IncomeTitle,它包含以下值:

let aryOne = ["salary","pension","salary","rent","wages","rent"]

第二个数组是 IncomeAmount,它包含以下值:

let aryTwo = ["100","900","100","800","5000","200"]

these two arrays values are related : eg-

salary is 100 and pension is 900 respectively salary is repeated 2 times so salary value should be 200

最后,我想要两个各自的数组,如下所示:

let incomeTitle = ["salary","pension","rent","wage"]
let incomeAmount = ["200", "900", "1000", "5000"]

我尝试这样做:

for(i=0;i<=noOfIncome;i++){
for(var j=i+1;j<=noOfIncome;j++){
if(this.incomeTitle[i]==this.incomeTitle[j]){
var abc= parseInt(this.incomeTitleAmount[i])+parseInt(this.incomeTitleAmount[j]);
this.incomeTitleAmount.push(abc);
this.incomeTitle.push(this.incomeTitle[i]);
}
}
this.incomeTitle.splice( i, 1 );
this.incomeTitleAmount.splice(i,1);
}

最佳答案

您可以为具有相同 array1 值的索引创建一个哈希表。

如果在哈希表中找到某个值,则可以将该值添加到哈希索引处的值,然后拼接两个数组。

如果没有找到,则获取索引并继续下一个索引。

var array1 = ["salary", "pension", "salary", "rent", "wages", "rent"],
array2 = ["100", "900", "100", "800", "5000", "200"],
hash = Object.create(null),
i = 0;

while (i < array1.length) {
if (array1[i] in hash) {
array2[hash[array1[i]]] = (+array2[hash[array1[i]]] + +array2[i]).toString();
array1.splice(i, 1);
array2.splice(i, 1);
continue;
}
hash[array1[i]] = i;
i++;
}

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

关于javascript - 删除数组中的重复值并合并与第二个数组关联的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47788959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com