In this post we will explore how to filter out falsy values from an array in JavaScript. Falsy values in JavaScript include false
, 0
, ""
, null
, undefined
, and NaN
.
We will see three ways by which we can do this, one is by using the filter method, second one is using reduce and third by the standard loop.
Using filter()
const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = array.filter(Boolean);
console.log(filteredArray); // Output: [1, 2, 3, 4, 5]
In the above example, we have created a new array with all elements that pass the test implemented by the provided function.
By passing Boolean
as the callback function, it effectively filters out all falsy values, since Boolean(value)
returns false
for any falsy value and true
for truthy values.
Using reduce()
const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = array.reduce((acc, curr) => {
if (Boolean(curr)) {
acc.push(curr);
}
return acc;
}, []);
console.log(filteredArray); // Output: [1, 2, 3, 4, 5]
In this example, we used the reduce method & pass two arguments, acc and curr. If curr is truthy we push it to acc. Initially the acc will be [] so at the end acc will contain only the truthy values.
Using loop
const array = [0, 1, false, 2, '', 3, null, 4, undefined, 5, NaN];
const filteredArray = [];
for (let i = 0; i < array.length; i++) {
if (array[i]) {
filteredArray.push(array[i]);
}
}
console.log(filteredArray); // Output: [1, 2, 3, 4, 5]
In this example, we loop through the array & for each item we check if its truthy using if condition. If the item is truthy we push it to filteredArray. In this way at the end filteredArray will contain only truthy values.
Similar Reads
- JavaScript – Sum of Digits of a NumberIn this article, we will learn how to find the sum of digits of a given number. The sum of digits can be obtained by… Read more: JavaScript – Sum of Digits of a Number
- JavaScript – Reverse a StringIn this article, we’ll look at three basic ways to reverse a string in JavaScript: the built-in reverse() method, a for loop, and the spread operator + reverse(). Using… Read more: JavaScript – Reverse a String
- JavaScript – Find the Intersection of Two ArraysIn this article, we will explore how to implement a function in JavaScript to find the intersection (Common Elements) of two arrays. The problem Write… Read more: JavaScript – Find the Intersection of Two Arrays
- JavaScript – Convert an array to an objectThere are many ways to convert an array to an object in JavaScript. Let’s explore some of the common approaches – Using reduce() In the… Read more: JavaScript – Convert an array to an object