Write a JavaScript function to remove.
null
,0
,""
,false
,undefined
andNaN
values from an array.
Sample array
[NaN, 0, 15, false, -22, '',undefined, 47, null]
Expected result
[15, -22, 47]
I am getting the result as : [ NaN ]
Is there any other way to perform this action?*
const arr = [0, NaN, 15, false, -22, '', undefined, 47, null]
let result = []
for (let i = 0; i <= arr.length; i++) {
if (arr[i] !== 0 && arr[i] !== false && arr[i] !== '' && arr[i] !== undefined && arr[i] !== null && !isNaN(arr[i]) === false) {
result.push(arr[i])
}
}
console.log(result)
2
Answers
Looks like you want to keep truthy values. You can pass filter and just use the value itself as the predicate using the identity function (
x => x
).If
filter
doesn’t work for you, it’s the equivalent of looping over the input, and if a condition is true, adding it to the output one.And here is the same thing by tracking the index yourself as in the original snippet:
Notice how the main point is that we are exploiting the concept of truthiness in JavaScript: every value at runtime can be evaluated as either
true
orfalse
, regardless of whether they are a boolean or not.0
,NaN
,false
,undefined
, andnull
are all evaluated tofalse
when a boolean is required (like when expressing a condition for anif
statement), while non-zero numbers are all evaluated totrue
.For more on the concept and how JavaScript decides whether a value is truthy or not, you can read more here: https://developer.mozilla.org/en-US/docs/Glossary/Truthy
you can filter the array to include only the numbers. The main issue in your code is the condition !isNaN(arr[i]) === false, which is not working as expected. Instead, you can use the typeof operator to check if the value is a number and isFinite to ensure it is not NaN.
Alternatively, you can use the filter method,