เรามีอาร์เรย์ของอ็อบเจ็กต์ต่อไปนี้ เราจำเป็นต้องรวมพวกมันเป็นหนึ่งเดียวเพื่อลบอ็อบเจ็กต์ที่มีค่าซ้ำซ้อนสำหรับชื่อคุณสมบัติ -
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 }
]