JavaScript: Remove null, 0, blank, false, undefined and NaN values from an array
JavaScript Array: Exercise-24 with Solution
Remove Falsy Values
Write a JavaScript function to remove. 'null', '0', '""', 'false', 'undefined' and 'NaN' values from an array.
Sample array: [NaN, 0, 15, false, -22, '',undefined, 47, null]
Expected result:
[15, -22, 47]
Visual Presentation:
Sample Solution:
JavaScript Code:
// Function to filter an array and remove falsy values
function filter_array(test_array) {
// Initialize index to -1, arr_length to the length of the array (if not provided, default to 0),
// resIndex to -1, and result as an empty array
var index = -1,
arr_length = test_array ? test_array.length : 0,
resIndex = -1,
result = [];
// Iterate through the elements of the test_array using a while loop
while (++index < arr_length) {
// Get the current value from the array
var value = test_array[index];
// Check if the value is truthy
if (value) {
// If truthy, add it to the result array and increment resIndex
result[++resIndex] = value;
}
}
// Return the filtered result array
return result;
}
// Output the result of the filter_array function with a sample array
console.log(filter_array([NaN, 0, 15, false, -22, '', undefined, 47, null]));
Output:
[15,-22,47]
Flowchart:
ES6 Version:
// Function to filter an array and remove falsy values
const filter_array = (test_array) => {
// Initialize index to -1, arr_length to the length of the array (if not provided, default to 0),
// resIndex to -1, and result as an empty array
let index = -1,
arr_length = test_array ? test_array.length : 0,
resIndex = -1,
result = [];
// Iterate through the elements of the test_array using a while loop
while (++index < arr_length) {
// Get the current value from the array
let value = test_array[index];
// Check if the value is truthy
if (value) {
// If truthy, add it to the result array and increment resIndex
result[++resIndex] = value;
}
}
// Return the filtered result array
return result;
};
// Output the result of the filter_array function with a sample array
console.log(filter_array([NaN, 0, 15, false, -22, '', undefined, 47, null]));
Live Demo:
See the Pen JavaScript - Remove null, 0, blank, false, undefined and NaN values from an array - array-ex- 24 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function to find the difference of two arrays.
Next: Write a JavaScript function to sort the following array of objects by title value.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics