ใช้ filter() กับฟังก์ชัน Boolean เพื่อเก็บค่า truthy เท่านั้น
filter(obj => obj) จะเก็บเฉพาะค่าที่เป็น truthy (ไม่ใช่ null, undefined, "", 0, false, NaN)
ตัวอย่างโค้ด
var names = [null, "John", null, "David", "", "Mike", null, undefined, "Bob", "Adam", null, null];
console.log("ก่อนกรอง = ");
console.log(names);
var filterNullValues = names.filter(obj => obj);
console.log("หลังกรองค่า falsy = ");
console.log(filterNullValues);
วิธีรัน
node fileName.js
ผลลัพธ์
ก่อนกรอง = [ null, 'John', null, 'David', '', 'Mike', null, undefined, 'Bob', 'Adam', null, null ]
หลังกรองค่า falsy = [ 'John', 'David', 'Mike', 'Bob', 'Adam' ]
คำอธิบาย
filter(obj => obj)ใช้ค่าเองเป็นเงื่อนไข: truthy คงไว้ falsy กรองทิ้ง- ค่า falsy ใน JS:
false, 0, "", null, undefined, NaN - ⚠️ ข้อควรระวัง: ค่า
0และfalseจะถูกกรองทิ้งด้วย!
กรองเฉพาะ null/undefined (เก็บ 0 และ false ไว้)
// เก็บทุกค่า ยกเว้น null และ undefined
const filtered = names.filter(v => v != null); // == null จับได้ทั้ง null และ undefined
// หรือชัดเจนกว่า
const filtered2 = names.filter(v => v !== null && v !== undefined);