Remove Empty Objects from an Array in JavaScript


Borislav Hadzhiev

Wed Oct 13 20212 min read


Photo by Briana Tozour

Remove Empty Objects from an Array #

To remove empty objects from an array:

  1. Call the filter() method passing it a function.
  2. On each iteration pass the current element to the Object.keys() method and check if the length of the keys array is not equal to 0.
  3. The filter method returns a new array containing only the elements that satisfy the condition.
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 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 use 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. This is not sufficient, because arrays also have a type of object in JavaScript.

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 are storing different types in the same array, chances are you're doing something wrong.

Further Reading #

Use the search field on my Home Page to filter through my more than 1,000 articles.