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?

2
  • Hmmmm, how would you feel about using lodash's _.uniqBy(your_array, 'label.title')? lodash.com/docs/4.17.15#uniqBy Commented Dec 18, 2020 at 7:50
  • You can see a similar question here Commented Dec 18, 2020 at 7:55

2 Answers 2

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);

Sign up to request clarification or add additional context in comments.

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.