[Fixed] Remove duplicate objects from an Array

Issue

I have an Array with duplicate objects, and I want to remove those duplicate objects. But I can’t seem to find a proper solution for it. What is my mistake over here?

The object is as below.

{name: "login", text: "Login"}
{name: "navigation", text: "Navigation"}
{name: "landing", text: "Landing Page"}
{name: "login", text: "Login"}
{name: "navigation", text: "Navigation"}
{name: "landing", text: "Landing Page"}

Below is my code where items has the array of objects.

this.subMenuItems = this.items.reduce((acc, current) => {
  const x = acc.find(item => item.name === current.name);
  if (!x) {
    return acc.concat([current]);
  } else {
    return acc;
  }
}, []);

Also you can refer the screenshot of the Console.log of the items variable
enter image description here

Solution

This one will assign this.subMenuItems an array containing only the first instance of each item because indexOf returns the first index where the object is found.

this.subMenuItems = this.items.filter((item, index, self) => self.indexOf(item) === index);

Leave a Reply

(*) Required, Your email will not be published