How to remove falsy values from an array in JavaScript?


In this article, you will understand how to remove false values from an array in JavaScript.

An array in JavaScript is a special variable that can hold more than one item. An array can be initialized using the keyword ‘const’ .Falsy values are nothing but boolean false values.

Example 1

The first way of achieving it is by iterating the array using a for-each loop and pushing the non-false values to another array and returning the array.

const inputArray = [true, false, false, true, null, 505, 101];
console.log("The input array is defined as: ")
console.log(inputArray)
function removeFalsey(inputArray) {
   const checkArray = [];      
   inputArray.forEach((k) => {
      if (k) {
         checkArray.push(k);
      }
   });
   return checkArray;
}
console.log("After removing the falsy elements from the array: ")
console.log(removeFalsey(inputArray));

Explanation

  • Step 1 − Define an array namely inputArray.

  • Step 2 −Define a function ‘removeFalsey’ that takes an array as input parameter.

  • Step 3 −In the function, define an empty array checkArray. Iterate over the inputArray using foreach loop, push the non-false elements to the newly defined array checkArray. Return the array.

  • Step 4 −Display the array as result.

Example 2

The other way of achieving this is to use the Array.filter() method to remove the falsy element.

const inputArray = [true, false, false, true, null, 505, 101];
console.log("The input array is defined as: ")
console.log(inputArray)     
function removeFalsey(input) {
   return inputArray.filter((k) => {
      if (k) {
         return k;
      }
   });
}
console.log("After removing the falsy elements from the array: ")
console.log(removeFalsey(inputArray));

Explanation

  • Step 1 −Define an array namely inputArray.

  • Step 2 −Define a function ‘removeFalsey’ that takes an array as input parameter.

  • Step 3 −In the function, call the filter() function on the array. In the filter() function, check if the element is a non-false element using an ‘if’ condition.

  • Step 4 −Display the array as result.

Updated on: 16-Feb-2023

249 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements