将两个 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.