To remove only null
values from a JavaScript array, you can do the following:
Using Array.prototype.filter()
When the provided callback function to Array.prototype.filter()
returns true
, the value from the original array is added to the resulting array, or ignored otherwise. Therefore, to add only non-null values to the resulting array you can implement a test in the callback function for the current value to not be null
, for example, like so:
// ES5+ const arr = [null, 'foo', '', 0, null, 'bar']; const newArr = arr.filter((item) => item !== null); console.log(newArr); // ['foo', '', 0', 'bar']
Using a Loop
You can simply iterate over an existing array and only add all non-null values to a new array, for example, like so:
const arr = [null, 'foo', '', 0, null, 'bar']; const newArr = []; for (let i = 0; i < arr.length; i++) { if (arr[i] !== null) { newArr.push(arr[i]); } } console.log(newArr); // ['foo', '', 0', 'bar']
You could also shorten this by using logical AND operator (&&
) with the condition to check for null
values on the left and the operation to add to the new array on the right. In this way, the value would only get added to the new array if the left side of the logical AND operator returns true
:
const arr = [null, 'foo', '', 0, null, 'bar']; const newArr = []; for (let i = 0; i < arr.length; i++) { arr[i] !== null && newArr.push(arr[i]); } console.log(newArr); // ['foo', '', 0', 'bar']
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.