Last updated on Jun 4, 2021 by Suraj Sharma
In this tutorial, you will learn to remove empty objects from an array in JavaScript
To remove empty objects from an array using the Array.filter method, you have to
Iterate through an array of objects using Array.filter
method and,
In each iteration check if the object is empty inside the callback function
const objects = [{}, {id: 1}, {}, [], {name: 'xyz'}, undefined];
objects.filter(
obj => !(obj && Object.keys(obj).length === 0 && obj.constructor === Object)
);
// [{id: 1}, [], {name: 'xyz'}, undefined];
Note: To remove both empty objects and empty arrays from the array, you can shorten the comparison to Object.keys().length === 0
, as arrays are also objects in JavaScript
objects.filter(
obj => !(obj && Object.keys(obj).length === 0)
);
// [{id: 1}, {name: 'xyz'}, undefined];
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.