find all truthy values in an integer array in javascript

You can find all truthy values in an integer array using the filter method in JavaScript. The filter method will return a new array with all the elements that pass the test implemented by the provided function. In this case, we can use a simple function that returns whether the element is truthy or not.

Here's the code:

index.tsx
const arr = [0, 1, 2, null, "hello", '', 3, undefined, NaN, false];

const truthyArr = arr.filter(Boolean);

console.log(truthyArr); // Output: [1, 2, "hello", 3]
163 chars
6 lines

In the above code, we first declare an array arr that contains a mix of falsy and truthy values. We then use the filter method on this array and pass the Boolean function as an argument. The Boolean function returns true for truthy values and false for falsy values. Therefore, the filter method will return a new array truthyArr that only contains the truthy values from the original array.

Finally, we log the truthyArr to the console to verify that we have successfully filtered out all falsy values from the original array.

related categories

gistlibby LogSnag