Để lọc null khỏi một mảng và chỉ hiển thị các giá trị không phải null, hãy sử dụng filter (). Sau đây là mã -
Ví dụ
var
names=[null,"John",null,"David","","Mike",null,undefined,"Bob","Adam",null,null];
console.log("Before filter null=");
console.log(names);
var filterNull=[];
filterNullValues=names.filter(obj=>obj);
console.log("After filtering the null values=");
console.log(filterNullValues); Để chạy chương trình trên, bạn cần sử dụng lệnh sau -
node fileName.js.
Đầu ra
Ở đây, tên tệp của tôi là demo148.js. Điều này sẽ tạo ra kết quả sau -
PS C:\Users\Amit\JavaScript-code> node demo148.js Before filter null=[ null, 'John', null, 'David', '', 'Mike', null, undefined, 'Bob', 'Adam', null, null ] After filtering the null values= [ 'John', 'David', 'Mike', 'Bob', 'Adam' ]