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

การลบรายการซ้ำในอาร์เรย์ที่มีค่า URL ด้วย JavaScript

สมมติเรามีอาร์เรย์ของออบเจกต์แบบนี้:

const arr = [
  {
    url: 'www.example.com/hello',
    id: "22"
  },
  {
    url: 'www.example.com/hello',
    id: "22"
  },
  {
    url: 'www.example.com/hello-how-are-you',
    id: "23"
  },
  {
    url: 'www.example.com/i-like-cats',
    id: "24"
  },
  {
    url: 'www.example.com/i-like-pie',
    id: "25"
  }
];

เราจำเป็นต้องเขียนฟังก์ชัน JavaScript ที่รับอาร์เรย์แบบนี้เข้ามา ฟังก์ชันควรลบออบเจกต์ที่มี key id ซ้ำกันออกจากอาร์เรย์ เราต้องทำโดยไม่ใช้ไลบรารีอย่าง underscore

ตัวอย่างโค้ด

const arr = [
  {
    url: 'www.example.com/hello',
    id: "22"
  },
  {
    url: 'www.example.com/hello',
    id: "22"
  },
  {
    url: 'www.example.com/hello-how-are-you',
    id: "23"
  },
  {
    url: 'www.example.com/i-like-cats',
    id: "24"
  },
  {
    url: 'www.example.com/i-like-pie',
    id: "25"
  }
];
const removeDuplicate = (arr = []) => {
  const map = {};
  for(let i = 0; i < arr.length; ){
    const { id } = arr[i];
    if(map.hasOwnProperty(id)){
      arr.splice(i, 1);
    }else{
      map[id] = true;
      i++;
    };
  };
};
removeDuplicate(arr);
console.log(arr);

ผลลัพธ์

ผลลัพธ์ที่แสดงในคอนโซลจะเป็นดังนี้:

[
  { url: 'www.example.com/hello', id: '22' },
  { url: 'www.example.com/hello-how-are-you', id: '23' },
  { url: 'www.example.com/i-like-cats', id: '24' },
  { url: 'www.example.com/i-like-pie', id: '25' }
]