While working on Codewars and attempting to solve a problem, I encountered an interesting question.
The task was to create a "toDense()" function that takes a sparse array as input and returns the corresponding dense array. An example test case provided was:
var sparse = [undefined, 2, null, , , 0, 6, null];
Test.assertSimilar( toDense(sparse), [2, 0, 6]);
I wrote the following code snippet to tackle this challenge:
function toDense(sparse){
function isBoolean(value)
{
if(value >= 0)
{
if(!(typeof(value) === 'object'))
return value;
}
}
return sparse.filter(isBoolean);
}
However, my solution did not yield the expected result of [2, 0, 6]. Instead, it only returned [2, 6]. This made me wonder why my if condition for 0 did not return its value, given that null is considered an object and 0 is a number.