We are required to write a JavaScript function that takes in an array that contains some false values. The function should remove all the null values from the array (if there are any) in place.
For example: If the input array is −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined, false, null];
Then the output should be −
const output = [12, 5, undefined, 0, false, 67, undefined, false];
Example
The code for this will be −
const arr = [12, 5, undefined, null, 0, false, null, 67, undefined, false, null]; const removeNullValues = arr => { for(let i = 0; i < arr.length; ){ // null's datatype is object and it is a false value // so only falsy object that exists in JavaScript is null if(typeof arr[i] === 'object' && !arr[i]){ arr.splice(i, 1); }else{ i++; continue; }; }; }; removeNullValues(arr); console.log(arr);
Output
The output in the console −
[ 12, 5, undefined, 0, false, 67, undefined, false ]