用两个JavaScript数组的现有成员和重复成员添加两个对象数组,以替换重复对象
我们具有以下对象数组,我们需要将它们合并为一个,以删除属性名称具有冗余值的对象-
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 }
]热门推荐
1 训练狗狗基础
2 怎么训练狗狗笑
3 怎么训练狗狗卧下
4 上海狗狗训练基地
5 训练狗狗排便
6 狗狗基础训练
8 如何训练狗狗装死
9 狗狗站姿训练
10 狗狗训练用品
11 训练狗狗吧
12 狗狗要怎么训练
13 怎么训练狗狗玩球
14 训练狗狗唤回
15 狗狗训练躺下
16 狗狗训练指令
17 狗狗的训练技巧
18 狗狗不好训练