อาร์เรย์แรก: [100, 110, 150, 180, 190, 175]
อาร์เรย์ที่สอง (ตัวกรอง): [100, 150, 175]
ใช้ filter() พร้อม thisArg เพื่อตัดสมาชิกที่ซ้ำกัน
ตัวอย่างโค้ด
var result = [100, 110, 150, 180, 190, 175].filter(
function(obj) {
return this.indexOf(obj) < 0;
},
[100, 150, 175]
);
console.log("After filter, the result is=");
console.log(result);รันด้วยคำสั่ง:
node fileName.js
ชื่อไฟล์: demo269.js
ผลลัพธ์
PS C:\Users\Amit\javascript-code> node demo269.js After filter, the result is= [ 110, 180, 190 ]
คำอธิบาย: パラメータที่สองของ filter() กำหนดค่า this ให้เป็นอาร์เรย์ตัวกรอง ใช้ this.indexOf(obj) < 0 ตรวจสอบว่าไม่อยู่ในอาร์เรย์ตัวกรอง
วิธีทันสมัย: const filterArr = [100, 150, 175]; const result = [100,110,150,180,190,175].filter(x => !filterArr.includes(x));