(Jump to Code | Demo) In order to find the duplicates, we need to compare two values. In case of numbers and strings, this is very simple. But when it comes to compare objects, arrays, functions etc., the problem begins. In this article I will show you the way to remove duplicate objects from array in JS.

If you want to learn about removing numbers and strings only then check out this article –

Let’s understand why comparing objects is not easy. First of all each key in object is reference by memory address. So basically its a collection of pointers to different memory addresses where values are stored. Secondly, you can store a very large number of elements in a single object. Thirdly, an object can contain other objects, arrays and even functions.

So, overall it’s tricky to compare an object with other.

Way to compare objects

You can follow these steps for object comparison-

  1. Check the lengths of both objects. If they are not equal then objects are not equal. No need to do anything else.
  2. Check if keys are same. If not then objects are not equal.
  3. At last, check the values corresponding to the keys. Accordingly equality of objects will be decided.

Code to remove duplicate objects

This code will compare objects with numbers, strings and nested objects & arrays as values. It won’t check the null, undefined and functions as values. We are using JSON.stringify() for converting objects to strings first and then comparing them.

var myArr = [
  {
    a: 5,
    b: "apple",
    c: ""
  },
  {
    a: 5,
    b: "apple"
  },
  {
    a: 5,
    b: "apple"
  },
  {
    b: 5,
    a: "apple"
  },
  {
    a: 5,
    b: {
      c: "yellow"
    }
  },
  {
    a: 5,
    b: {
      d: "yellow"
    }
  },
  {
    a: 5,
    b: {
      c: "yellow"
    }
  }
];

const removeDuplicateObjects = (myArr) => {
  var uniqueArr = [];
  var objStrings = [];

  myArr.forEach((element) => {
    if (typeof element === "object" && element !== null) {
      var eleString = JSON.stringify(element);
      if (!objStrings.includes(eleString)) {
        uniqueArr.push(element);
        objStrings.push(eleString);
      }
    }
  });

  return uniqueArr;
};

myArr = removeDuplicateObjects(myArr);

    Tweet this to help others

This is good for all the general use cases but if you need more in depth comparisons then you should consider using libraries like Lodash.

Live Demo

You may also like –

Tagged in:

,

Comments

About the Author

akamit

I am Akash Mittal, an overall computer scientist. If you want to guest post, need help in your projects, want to advertise, Feel free to contact me at [email protected]

View All Articles