將兩個 JavaSipt 陣列中的包含已存在和重複成員的兩個物件陣列相加,並替換掉重複的部分


我們有以下物件陣列,我們需要將它們合併到一個數組中,並移除屬性名為重複值的物件 −

const first = [{
   name: 'Rahul',
   age: 23
}, {
   name: 'Ramesh',
   age: 27
}, {
   name: 'Vikram',
   age: 35
}, {
   name: 'Harsh',
   age: 34
}, {
   name: 'Vijay',
   age: 21
}];
const second = [{
   name: 'Vijay',
   age: 21
}, {
   name: 'Vikky',
   age: 20
}, {
   name: 'Joy',
   age: 26
}, {
   name: 'Vijay',
   age: 21
}, {
   name: 'Harsh',
   age: 34
}, ]

我們定義一個名為 combineArray 的函式,將兩個要合併的陣列作為引數輸入,並返回一個新陣列 −

const combineArray = (first, second) => {
   const combinedArray = [];
   const map = {};
   first.forEach(firstEl => {
      if(!map[firstEl.name]){
         map[firstEl.name] = firstEl;
         combinedArray.push(firstEl);
      }
   });
   second.forEach(secondEl => {
      if(!map[secondEl.name]){
         map[secondEl.name] = secondEl;
         combinedArray.push(secondEl);
      }
   })
   return combinedArray;
}
console.log(combineArray(first, second));

此函式不僅可以確保移除第二個陣列中的重複項,而且還可以移除第一個陣列中已存在的任何重複項。

以下是完整程式碼 −

示例

const first = [{
   name: 'Rahul',
   age: 23
}, {
   name: 'Ramesh',
   age: 27
}, {
   name: 'Vikram',
   age: 35
}, {
   name: 'Harsh',
   age: 34
}, {
   name: 'Vijay',
   age: 21
}];
   const second = [{
      name: 'Vijay',
      age: 21
}, {
   name: 'Vikky',
   age: 20
}, {
   name: 'Joy',
   age: 26
}, {
   name: 'Vijay',
   age: 21
}, {
   name: 'Harsh',
   age: 34
}, ]
const combineArray = (first, second) => {
   const combinedArray = [];
   const map = {};
   first.forEach(firstEl => {
      if(!map[firstEl.name]){
         map[firstEl.name] = firstEl;
         combinedArray.push(firstEl);
      }
   });
   second.forEach(secondEl => {
      if(!map[secondEl.name]){
         map[secondEl.name] = secondEl;
         combinedArray.push(secondEl);
      }
   })
   return combinedArray;
}
console.log(combineArray(first, second));

輸出

控制檯輸出將是 −

[
   { name: 'Rahul', age: 23 },{ name: 'Ramesh', age: 27 },{ name: 'Vikram', age: 35 },
   { name: 'Harsh', age: 34 },{ name: 'Vijay', age: 21 },{ name: 'Vikky', age: 20 },
   { name: 'Joy', age: 26 }
]

更新於: 2020 年 8 月 18 日

108 瀏覽量

開啟你的職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.