เรามีอาร์เรย์ของตัวเลข/สตริงที่มีค่าซ้ำกัน ต้องลบค่าเหล่านี้ออกจากอาร์เรย์โดยไม่สร้างอาร์เรย์ใหม่หรือเก็บค่าซ้ำไว้ที่อื่น
เราจะใช้ Array.prototype.splice() เพื่อลบรายการแบบ in-place และช่วยจาก Array.prototype.indexOf() และ Array.prototype.lastIndexOf() เพื่อตรวจสอบการซ้ำของแต่ละองค์ประกอบ
ตัวอย่าง
const arr = [1, 4, 6, 1, 2, 5, 2, 1, 6, 8, 7, 5]; arr.forEach((el, ind, array) => { if(array.indexOf(el) !== array.lastIndexOf(el)){ array.splice(ind, 1); } }); console.log(arr);ผลลัพธ์
ผลลัพธ์ในคอนโซลจะเป็นดังนี้
[ 4, 1, 5, 2, 6, 8, 7 ]