Remove empty elements from an array in Javascript
EDIT: This question was answered almost nine years ago when there were not many useful built-in methods in the Array.prototype
.
Now, certainly, I would recommend you to use the filter
method.
Take in mind that this method will return you a new array with the elements that pass the criteria of the callback function you provide to it.
For example, if you want to remove null
or undefined
values:
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) {
return el != null;
});
console.log(filtered);
How to remove empty array values ( ) from an array?
You could use the filter like:
arr = arr.filter(item => item);
Example:
let arr = ['One', 'Two', '', 'Four', '', ''];
arr = arr.filter(item => item);
console.log(arr);
// Result
// ['One', 'Two', 'Four']
Because an empty string evaluates to boolean false
.
It works with all falsy values like 0
, false
, null
, undefined
, ''
, etc.
DEMO
If you want to keep some values like number 0
(zero) you could use item !== undefined
. This filters only undefined values. Keep in mind to trim your string or check with regex to ensure empty strings without whitespaces.
How to remove empty trailing values and Carriage Return in JS Array?
I don't think there's any magic bullet here, just a loop checking for the values you want to remove, directly or with a regular expression. For instance, to remove blank strings and "\r"
:
while (array.length) { // Loop while there are still entries
const last = array[array.length - 1]; // Get the last entry without removing it
if (last !== "" && last !== "\r") { // Is this one to remove?
break; // No, stop
}
--array.length; // Yes, remove and keep looping
}
Live Example:
const array = ['', 'Apple', '', 'Banana', '', 'Guava', '', '', '', '\r'];
while (array.length) { // Loop while there are still entries
const last = array[array.length - 1]; // Get the last entry without removing it
if (last !== "" && last !== "\r") { // Is this one to remove?
break; // No, stop
}
--array.length; // Yes, remove and keep looping
}
console.log(array);
Remove empty values from array of objects only if the value is empty in all objects
If you don't mind mutating the original array
object. Here's a solution utilizing some array functions.
let array = [
{ name: 'John', age: '18', address: '' },
{ name: 'George', age: '', address: '' },
{ name: 'Kevin', age: '25', address: '' }
]
Object.keys(array[0])
.filter(k => array.every(obj => !obj[k]))
.forEach(k => array.forEach(obj => delete obj[k]));
console.log(array);
Remove empty array from array of objects
- Using
Array#map
, iterate over the array - Using
Object#entries
, get the list of entries for the current object - Using
Array#filter
, filter the entries whose value is an empty array - Using
Object#fromEntries
, return the current object containing the filtered entries
const arr = [
{
"2022-03-10": [
{ "Age": "31", "Last": "Craig", "Name": "Carlos", "Time": "11:00am - 12:00pm", "Type": "Consulta General", "read": false }
],
"2022-03-26": [
{ "Age": "31", "Last": "Craig", "Name": "Carlos", "Time": "11:00am - 12:00pm", "Type": "Follow Up", "read": false }
],
"2022-03-27": [],
"2022-03-31": [
{ "Age": "31", "Last": "Craig", "Name": "Carlos", "Time": "11:00am - 12:00pm", "Type": "Valoraciones Funcionales", "read": false }
]
}
];
const filtered = arr.map(obj =>
Object.fromEntries(
Object.entries(obj).filter(([key, value]) => value.length > 0)
)
);
console.log(filtered);
Related Topics
How to Find the Sum of an Array of Numbers
JavaScript: Natural Sort of Alphanumerical Strings
Resolve Promises One After Another (I.E. in Sequence)
What Is the Purpose of Node.Js Module.Exports and How to Use It
Get JavaScript Object from Array of Objects by Value of Property
How to Declare a Namespace in JavaScript
Location of Parenthesis For Auto-Executing Anonymous JavaScript Functions
How to Parse CSV Data With JavaScript
How to Add Two Strings as If They Were Numbers
Use Basic Authentication With Jquery and Ajax
Updating Address Bar With New Url Without Hash or Reloading the Page
Async/Await Implicitly Returns Promise
Remove Empty Elements from an Array in JavaScript
Rails 4: How to Use $(Document).Ready() With Turbo-Links
When Are You Supposed to Use Escape Instead of Encodeuri/Encodeuricomponent
Jquery Animate Backgroundcolor