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

กรองอาเรย์ด้วย filter() และ includes() ใน JavaScript

ใช้ filter() ร่วมกับ includes() เพื่อคัดกรองค่าที่ไม่อยู่ในรายการที่กำหนด

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

const names = ['John', 'David', 'Mike', 'Sam', 'Carol', 'Bob'];

console.log("The names are=");
console.log(names);

var nameObject = names.filter((allNameObject) => 
    !['David', 'Mike', 'Sam', 'Carol'].includes(allNameObject)
);

console.log("After filter=");
console.log(nameObject);

วิธีรันโปรแกรม

ใช้คำสั่ง node fileName.js (เช่น node demo65.js)

ผลลัพธ์

The names= [ 'John', 'David', 'Mike', 'Sam', 'Carol', 'Bob' ]
After filter= [ 'John', 'Bob' ]