0

I have an Array Object as below:

[
   {
     label : { title: 'Home'},
     url: '/'
   },
   {
     label : { title: 'Purchasing'},
     url: '//purchasing///'
   },
   {
     label : { title: 'Purchase Order Details'},
     url: '//purchasing////2002'
   },
   {
     label : { title: 'Purchase Order Details'},
     url: '//purchasing////2002/'
   }
]

I want to remove the object (duplicate) based on it's title property. For example: here 3rd & 4th objects have similar title properties.

How to do this?

Unknown Coder
  • 1,510
  • 2
  • 28
  • 56
  • Hmmmm, how would you feel about using lodash's _.uniqBy(your_array, 'label.title')? https://lodash.com/docs/4.17.15#uniqBy – Bruno Lipovac Dec 18 '20 at 07:50
  • You can see a similar question [here](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – hyojoon Dec 18 '20 at 07:55

2 Answers2

2

You could use Array.prototype.reduce() method. Traverse the array and group all data by title.

const data = [
  {
    label: { title: 'Home' },
    url: '/',
  },
  {
    label: { title: 'Purchasing' },
    url: '//purchasing///',
  },
  {
    label: { title: 'Purchase Order Details' },
    url: '//purchasing////2002',
  },
  {
    label: { title: 'Purchase Order Details' },
    url: '//purchasing////2002/',
  },
];
const ret = Object.values(
  data.reduce((prev, c) => {
    const p = prev;
    const key = c.label.title;
    p[key] = { ...c };
    return p;
  }, {})
);
console.log(ret);
mr hr
  • 3,162
  • 2
  • 9
  • 19
0

Solution via Array.filter()

let uniq = {};
let arr = [
   {
     label : { title: 'Home'},
     url: '/'
   },
   {
     label : { title: 'Purchasing'},
     url: '//purchasing///'
   },
   {
     label : { title: 'Purchase Order Details'},
     url: '//purchasing////2002'
   },
   {
     label : { title: 'Purchase Order Details'},
     url: '//purchasing////2002/'
   }
]

let filtered = arr.filter(obj => !uniq[obj.label.title] && (uniq[obj.label.title]=true));

console.log(filtered);
hyojoon
  • 493
  • 1
  • 6
  • 17