JSFiddle - React, Tailwind, and code Playground
by anonystick
JavaScript
// không dùng filter
function bouncerWithoutFilter(arr) {
// Don't show a false ID to this bouncer.
var falsy;
var trueArr = [];
for (i = 0; i < arr.length; i++) {
falsy = Boolean(arr[i]);
if (falsy === true) {
trueArr.push(arr[i]);
}
}
return trueArr;
}
console.log(bouncerWithoutFilter([7, "ate", "", false, undefined, null, 9]))
// dùng filter
function bouncerWithFilter(arr) {
return arr.filter(element => Boolean(element) === true)
//or
//return arr.filter(element => element)
//or
return arr.filter(Boolean)
}
console.log(bouncerWithFilter([7, "ate", "", false, undefined, null, 9]))
someArray = [{name: 'Jon Snow', age: '20'}, undefined, 400, null, 'from Winterfell',,,'',, null];
console.log(someArray.filter(Boolean))