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

ลบอ็อบเจกต์ซ้ำออกจากอาร์เรย์ใน JavaScript

เราต้องเขียนฟังก์ชันลบอ็อบเจกต์ซ้ำออกจากอาร์เรย์ คืนอาร์เรย์ใหม่ ถือว่าอ็อบเจกต์ซ้ำกันถ้าทั้งสองมีจำนวน key เท่ากัน key เหมือนกันหมด และ value ทุก key เหมือนกันหมด

เขียนโค้ด

เราจะใช้ Map เก็บอ็อบเจกต์ที่แตกต่างในรูป stringified และเมื่อเจอ key ซ้ำ ข้ามไป มิฉะนั้น push อ็อบเจกต์เข้าไปในอาร์เรย์ใหม่

ตัวอย่าง

const arr = [
  {
    "timestamp": 564328370007,
    "message": "It will rain today"
  },
  {
    "timestamp": 164328302520,
    "message": "will it rain today"
  },
  {
    "timestamp": 564328370007,
    "message": "It will rain today"
  },
  {
    "timestamp": 564328370007,
    "message": "It will rain today"
  }
];
const map = {};
const newArray = [];
arr.forEach(el => {
  if(!map[JSON.stringify(el)]){
    map[JSON.stringify(el)] = true;
    newArray.push(el);
  }
});
console.log(newArray);

ผลลัพธ์

ผลลัพธ์ในคอนโซลจะเป็น

[
  { timestamp: 564328370007, message: 'It will rain today' },
  { timestamp: 164328302520, message: 'will it rain today' }
]