Remove Empty Objects from an Array in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 13 20212 min read

banner

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.
index.js
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.

index.js
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.
index.js
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.

index.js
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.

index.js
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.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee