Home  >  Article  >  Web Front-end  >  How to remove false values ​​from JavaScript array?

How to remove false values ​​from JavaScript array?

PHPz
PHPzforward
2023-08-24 19:17:061061browse

如何从 JavaScript 数组中删除假值?

In this article, you will learn how to remove error values ​​from an array in JavaScript.

An array in JavaScript is a special type of variable that can hold multiple items. Arrays can be initialized using the keyword "const". Falsy values ​​are nothing but Boolean false values.

Example 1

The first way to implement it is to use a for-each loop to iterate over the array and push the non-false values ​​to another array and return that 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));

illustrate

  • Step 1 - Define an array, i.e. inputArray.

  • Step 2 - Define a function "removeFalsey" that takes an array as an input parameter.

  • Step 3 - In the function, define an empty array checkArray. Use a foreach loop to iterate over the inputArray, pushing non-false elements to the newly defined array checkArray. Return an array.

  • Step 4 - Display the array as the result.

Example 2

Another way to achieve this is to use the Array.filter() method to remove spurious elements.

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));

illustrate

  • Step 1 - Define an array, i.e. inputArray.

  • Step 2 - Define a function "removeFalsey" that takes an array as an input parameter.

  • Step 3 - In the function, call the filter() function on the array. In the filter() function, use an "if" condition to check if an element is non-false.

  • Step 4 - Display the array as the result.

The above is the detailed content of How to remove false values ​​from JavaScript array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete