13

I am trying to remove duplicate value objects in an array but not working... I think duplicate function is working but not reflecting in li list. Can you find out where I have to change?

My service file:

 addComp(Names,c){   
 this.item.push({ name: Names, componentid: c});
 this.uniqueArray = this.removeDuplicates(this.item, "name"); //this line issue
 this.item=this.uniqueArray; //this line issue
 }

6 Answers 6

22
const result = Array.from(this.item.reduce((m, t) => m.set(t.name, t), new Map()).values());

This might be fix your issue.

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

Comments

12
this.item = this.item.filter((el, i, a) => i === a.indexOf(el))

Comments

7

If addComp is the only place you modify this.item, just check for existing prior to insertion. Duplicates will never get put in the array, so you'll never have to trim them.

addComp(Names,c){
  let item = {name: Names, componentid: c};
  if (this.item.find((test) => test.name === Names) === undefined) {
    this.item.push(item);
  }
}

Alternatively, if there are other places that you're modifying this.item, you should be stripping duplicates in a more expected place. Stripping them as a side-effect of the addComp function is unexpected. However, you could do it...

addComp(Names,c){
  this.item.push({name: Names, componentid: c});
  this.item = this.item.filter((test, index, array) =>
     index === array.findIndex((findTest) =>
        findTest.name === test.name
     )
  );
}

2 Comments

Thanks..Working fine
I have some question in angular 6..Can you answer me?
2

This will remove existing duplicates in this.item

const item = [...new Set(this.item)];

This is a more updated way to do this. this will check for existing prior to insertion. And if item is not in this.item then this.item.indexOf(item) = -1

This is the best way to prevent pushing duplicate value objects in to an array

addComp(Names,c){
  let item = {name: Names, componentid: c};
  if (this.item.indexOf(item) === -1) {
    this.item.push(item);
  }
}

Comments

0

This will fix the bug

const uniqueObjectArray = [...new Map(arrayOfObjectsWithDuplicates.map(item => [item[key], item])).values()]

Comments

0

For instance, you have an array:

var ar = [ 
{key: 1, value: 'aa'},
{key: 2, value: 'bb'},
{key: 1, value: 'aa'},
]

To filter it and eliminate duplicates based on a key, use the following:

ar.filter((el, i, a) => i === a.indexOf(a.find(f => f.key === el.key)))

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.