Write a function to remove all falsy values from an array. In JavaScript, falsy values are values that are considered false when encountered in a Boolean context. These values include false
, 0
, ""
(empty string), null
, undefined
, and NaN
.
Input: array = [0, "Hello", false, 42, "", NaN, true, null, "World"]
Output: ["Hello", 42, true, "World"]
function removeFalsyValuesFilter(arr) {
return arr.filter(Boolean);
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesFilter(array1); //output: ["Hello", 42, true, "World"]
function removeFalsyValuesForLoop(arr) {
const result = [];
for (const value of arr) {
if (value) {
result.push(value);
}
}
return result;
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesForLoop(array1); //output: ["Hello", 42, true, "World"]
function removeFalsyValuesForEach(arr) {
const result = [];
arr.forEach(value => {
if (value) {
result.push(value);
}
});
return result;
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesForEach(array1); //output: ["Hello", 42, true, "World"]
function removeFalsyValuesReduce(arr) {
return arr.reduce((acc, value) => {
if (value) {
acc.push(value);
}
return acc;
}, []);
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesReduce(array1); //output: ["Hello", 42, true, "World"]
function removeFalsyValuesWhileLoop(arr) {
const result = [];
let index = 0;
while (index < arr.length) {
if (arr[index]) {
result.push(arr[index]);
}
index++;
}
return result;
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesWhileLoop(array1); //output: ["Hello", 42, true, "World"]
function removeFalsyValuesMapFilter(arr) {
return arr.map(value => value).filter(Boolean);
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesMapFilter(array1); //output: ["Hello", 42, true, "World"]
function removeFalsyValuesSome(arr) {
const result = [];
arr.some(value => {
if (value) {
result.push(value);
}
return false; // Continue checking all values
});
return result;
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesSome(array1); //output: ["Hello", 42, true, "World"]
function removeFalsyValuesArrayFrom(arr) {
return Array.from(arr).filter(Boolean);
}
const array1 = [0, "Hello", false, 42, "", NaN, true, null, "World"];
removeFalsyValuesArrayFrom(array1); //output: ["Hello", 42, true, "World"]