如何合并Javascript中的两个数组去重复项目并将其数量相加

时间:2016-08-02 23:57:33

标签: javascript arrays merge

我有两个JavaScript数组:

const array1 = [
  {id: 01, qnty: 2}, 
  {id: 02, qnty: 1}, 
  {id: 03, qnty: 1}
];

const array2 = [{id: 02, qnty: 3}];

我希望输出为:

const newArray = [
  {id: 01, qnty: 2},
  {id: 02, qnty: 4},
  {id: 03, qnty: 1},
];

输出数组应删除具有相同id的项目,并将其qnty值相加。

1 个答案:

答案 0 :(得分:1)

function inArray(arr, obj) {
  for (var i = 0; i < arr.length; i++) {
    if (arr[i].id == obj.id) {
      return i;
    }
  }
  return -1;
}


const array1 = [{  id: 01,  qnty: 2}, {  id: 02,
  qnty: 1}, {  id: 03,  qnty: 1}];



const array2 = [{  id: 02,  qnty: 3}];

var newArray = array1.slice(0); //clone array1
for (var i = 0; i < array2.length; i++) {
  var obj = array2[i];
  var index = inArray(array1, obj);
  if( index== -1){
     newArray.push(obj);
  }else {
    newArray[index] = { id: newArray[index].id,  qnty: newArray[index].qnty + obj.qnty } 
  }
}

console.log(newArray);
const newArray = [ {id: 01, qnty: 2}, {id: 02, qnty: 4}, {id: 03, qnty: 1}, ];