Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

รวมอาร์เรย์อ็อบเจกต์สองชุด โดยแทนที่สมาชิกซ้ำใน JavaScript

เรามีอาร์เรย์อ็อบเจกต์สองชุด ต้องการรวมเข้าด้วยกันและลบอ็อบเจกต์ที่มีค่าซ้ำกันในคุณสมบัติ name

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 }
]