How to remove empty objects from an array in JavaScript

#javascript

Last updated on Jun 4, 2021 by Suraj Sharma


In this tutorial, you will learn to remove empty objects from an array in JavaScript


Remove empty objects from an array


To remove empty objects from an array using the Array.filter method, you have to

  1. Iterate through an array of objects using Array.filter method and,

  2. In each iteration check if the object is empty inside the callback function


Solution

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 a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.