"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Write a function that filters out all the falsy values from a given array.

Write a function that filters out all the falsy values from a given array.

Published on 2024-08-21
Browse:906

Write a function that filters out all the falsy values from a given array.

 const removeFalsyValues = (arr) => {
    let truthy = []

    for(let i = 0; i 



Falsy values in JavaScript are values that are considered false when evaluated in a Boolean context. These include0, false, "" (an empty string), undefined, NaN, and null.

Here's how the function works:

  • Initialize an empty array: The function starts by creating an empty array called truthy. This will be used to store the values from the original array that are not falsy.
  • Loop through the array: The function uses a for loop to go through each element in the input array arr.
  • Check if the element is truthy: Inside the loop, there's an if statement that checks if the current element (arr[i]) is truthy. If the element is truthy (meaning it's not one of the falsy values), it gets added to the truthy array.
  • Return the truthy array: After the loop has gone through all the elements, the function returns the truthy array, which now contains only the truthy values.
  • The input array is [0, 1, false, 2, "", 3, undefined, NaN, null].
  • The function will loop through each element and remove the falsy ones (0, false, "", undefined, NaN, null).
  • The remaining truthy values (1, 2, 3) are returned in a new array:[1, 2, 3].

So, the output of this code will be:removeFalsyValue [1, 2, 3].

Release Statement This article is reproduced at: https://dev.to/ajaymarathe/create-a-function-which-will-remove-all-the-falsy-values-from-given-array-1ilf?1 If there is any infringement, please contact study_golang @163.comdelete
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3