I have an array arr1 = [0,1,false,2,undefined,'',null,3]
The expected result is removing all the falsy values and return the array with only truthy ones like this => [1, 2, 3]
But, I instead got this =>[ 1, undefined]
The code I've wrote is: click this link to see the code
for(let i=1;i<=arr1.length;i++)
{
if(!arr1[i-1])
{
arr1.splice(i-1,i);
}
}
console.log(arr1);
Line 1 - Here, I am looping through the array upto the array length.
Line 2 - At this step I am checking for the false values. If the values are falsy then enters inside the block.
Line 3 - At this step I want to remove the element from the array using splice. Since, I have started the array from index 1 so I want to remove the element from index i-1 to index i.
For instance, If I want to remove 'false' element from my array whose index is 2 but array index is pointing at 3, so I splice it from index i-1 which is 2 upto index i which is 3. Then, the element will be removed from the array.
Line 4 - Prints the array arr1 in the console.
The output should be [1,2,3] but what I got is [ 1, undefined]
Can someone help me with where I was wrong and I also tried filter method and Boolean constructor then the desired output is coming. But, I wanted to know where my code went wrong. Please, hep me with this.
You can easily filter array values to check whether they are falsy or not by converting the values to a boolean:
[0,1,false,2,undefined,'',null,3].filter(Boolean) // [1, 2, 3]
Hope this helps!
const arr = [1,2,"foo", "bar", undefined,0,null,3];
const newArray = arr.filter(Boolean);
console.log(newArray);
Filter is the best way to remove unwanted items from an array.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
By passing the Boolean type as a callback it'll just convert all values to booleans as a filter test and return only those values that are true for Boolean(val)
You can check truthy/falsy values by putting it in an if like this.
const arr1 = [0,1,false,2,undefined,'',null,3];
let result = [];
arr1.forEach(o => {
if (o) result.push(o);
});
console.log(result);