In javascript, I want to remove undefined values, but keep the values 0 and null from an array.
[ 1, 2, 3, undefined, 0, null ]
How can I do it cleanly?
To remove all undefined values from an array:Create an empty array that will store the results. Use the forEach() method to iterate over the array. Check if each element is not equal to undefined . If the condition is met, push the element into the results array.
To remove all undefined values from an object:Use the Object. keys() method to get an array of the object's keys. Use the forEach() method to iterate over the array and delete all undefined values using the delete operator.
To remove all empty elements from an array:Call the filter() method, passing it a function. For each element in the array, check if its value is not equal to null and it's not equal to undefined . The filter method returns a new array containing only the elements that satisfy the condition.
To remove a null from an object with lodash, you can use the omitBy() function. If you want to remove both null and undefined , you can use . isNull or non-strict equality.
Using lodash, the following remove only undefined values from the array: var array = [ 1, 2, 3, undefined, 0, null ]; _.filter (array, function (a) { return !_.isUndefined (a) } --> [ 1, 2, 3, 0, null ] Or, the following will remove the undefined, 0 and null values: _.filter (array) --> [1, 2, 3]
The function is predicate and checks each element in an array is not equal to undefined. The filter () method will return the new Array, excluding the undefined values The filter method will not modify the contents of the original Array. It returns a new Array containing the elements that have satisfied the condition.
To remove ‘0’. ‘undefined’ and empty values, you need to use the concept of splice (). Let’s say the following is our array − To run the above program, you need to use the following command − node fileName.js. Here, my file name is demo88.js.
To remove all holes from an array, the idea is to call the filter () method with a callback function that returns true. Note that this approach only remove holes from the array but doesn’t remove any of the other falsy values. 4. Remove all falsy values
You can use _.compact(array);
Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are falsey.
See: https://lodash.com/docs/4.15.0#compact
The best way using lodash is _.without
Example:
const newArray = _.without([1,2,3,undefined,0,null], undefined);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With