การลบค่าซ้ำ (Remove Duplicates)
ลบ duplicates ในอาร์เรย์มีหลาย logical methods แต ES6+ มี methods ทำให้ง่าย: Set() และ filter()
Set()
Set() รับค่า unique values เท่านั้น ลบ duplicates อัตโนมัติ ไม่ต้องใช้ logic เอง
ตัวอย่าง
<html> <body> <script>
var dupNames = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim'];
var uniArr = [...new Set(dupNames)];
document.write("Before removing: " + dupNames);
document.write("<br>");
document.write("After using Set(): " + uniArr);
</script> </body> </html>
ผลลัพธ์
Before removing: John,Ram,Rahim,Remo,Ram,Rahim After using Set(): John,Ram,Rahim,Remo
filter()
ใช้ filter() ตรวจสอบแต่ละ element ว่าซ้ำ 2 ครั้งขึ้นไป อนุญาตให้แสดงแค่ 1 ครั้ง
ตัวอย่าง
<html> <body> <script>
var dupnam = ['John', 'Ram', 'Rahim', 'Remo', 'Ram', 'Rahim'];
var x = (dupname) => dupname.filter((v, i) => dupname.indexOf(v) === i);
document.write("Before removing: " + dupnam);
document.write("<br>");
document.write("After filter(): " + x(dupnam));
</script> </body> </html>
ผลลัพธ์
Before removing: John,Ram,Rahim,Remo,Ram,Rahim After filter(): John,Ram,Rahim,Remo