Remove Empty Objects from an Array in JavaScript


Borislav Hadzhiev

Last updated: Jul 25, 2022


Photo from Unsplash

Remove Empty Objects from an Array #

To remove empty objects from an array:

  1. Use the Array.filter() method to iterate over the array..
  2. Pass each object to the Object.keys() method and check if the length of keys is not equal to 0.
  3. The filter method will return a new array that doesn't contain empty objects.
const arr = [{}, {id: 1}, {}, {id: 2}, {}]; const results = arr.filter(element => { if (Object.keys(element).length !== 0) { return true; } return false; }); // 👇️ [{id: 1}, {id: 2}] console.log(results);

The function we passed to the Array.filter method gets invoked with each element (object) in the array.

If the function returns a truthy value, the filter method adds the element to the results array.

The Object.keys method returns an array containing the object's keys.

console.log(Object.keys({})); // 👉️ [] console.log(Object.keys({id: 1})); // 👉️ ['id']

If the object has no key-value pairs, the method returns an empty array.

We only return true and add the object to the results array if it has at least 1 key-value pair.

Note that the Object.keys(obj).length method would return 0 if called with an empty array [] or the number 0.
console.log(Object.keys(0).length); // 👉️ 0 console.log(Object.keys([]).length); // 👉️ 0

If your array contains types other than objects, use the following approach to remove only the empty objects from the array.

const arr = [{}, {id: 1}, 'a', 0, {}, []]; const results = arr.filter(element => { if ( typeof element === 'object' && !Array.isArray(element) && Object.keys(element).length === 0 ) { return false; } else { return true; } }); // 👇️ [{id: 1}, 'a', 0, []] console.log(results);

We used the && (and) operator to specify that all conditions have to be met for the if block to run.

We first check if the element has a type of object, but this is not sufficient because JavaScript arrays also have a type of object.

console.log(typeof []) // 👉️ 'object'

Then we check that the element is not an array and that the object is empty.

If all these conditions are met, we know we have an empty object and it should not be added to the results array, therefore we return false.

In all other cases the array element is not an empty object and gets added to the new array.

Most of the time it's an anti-pattern to store multiple different types in an array. If you need to store different types in the same array, chances are you're doing something wrong.

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.