Home > database >  How can I remove null values from an array?
How can I remove null values from an array?

Time:12-10

(https://i.stack.imgur.com/SDDQC.png)

I want to remove the null value from the array, how should I do that?

I tried the following function, but it doesn't seem to solve the problem:

function removeNull(array) {
    return array.filter(x => x !== null)
}

CodePudding user response:

to remove null values or undefined values from an array use the Array. filter() method to iterate over the array . check if each value is not equal to undefined and return the result. the filter() method will return the array which is new and does not contain any null values

CodePudding user response:

.filter(x => x != null) works as expected. You can shorten that to .filter(Boolean) if your array item values do not contain falsy values such as 0:

console.log('option 1: ', [0, 1, 2, null, 3].filter(x => x != null))
// [0, 1, 2, 3])
console.log('option 2: ', [0, 1, 2, null, 3].filter(Boolean))
// [1, 2, 3])

  • Related