我们具有以下对象数组,我们需要将它们合并为一个,以删除属性名称具有冗余值的对象-
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 } ]