-1

I need to check if an array contains duplicated values.

Lets say I have the following array of arrays:

array = [
  { id: 123, name: 'Emily', address: 'UK' },
  { id: 123, name: 'Ross', address: 'USA' },
  { id: 157, name: 'Joey', address: 'Italy' },
];

As you can see, I have 2 arrays, aving the same ID id=123, and I need to detect these 2 rows, so we can clean the data we have.

P.S. I am only interested in checking duplication on IDs and Names at the same time.

I did the following logic, but it doesn't make sense, as it returns rows more than the existed ones:

ngOnInit() {
    this.array.forEach((row) => {
      this.array.find(element => {
        if (element['id'] === row['id']) {
          console.log(row)
        }
      })
    })
  }

The output is like:

123 Emily

123 Emily

123 Ross

123 Ross

157 Joey

My needed out output is as the following:

123 Emily

123 Ross

Here is a stackblitz.

2
  • 1
    That isn't an array of arrays. That's an array of objects. Commented Apr 6, 2020 at 8:23
  • There are at least a dozen previous questions about finding duplicates of objects in arrays. Have you worked through their answers? This is an often-asked question that's bound to have been answered sufficiently in the past. Commented Apr 6, 2020 at 8:24

1 Answer 1

1

You can use filter and map like this to get a distinct-like behaviour:

function distinct(myArray, prop) {
    return myArray.filter((obj, pos, arr) => {
        return arr.map(mapObj => mapObj[prop]).indexOf(obj[prop]) === pos;
    });
}
Sign up to request clarification or add additional context in comments.

4 Comments

This is an often-asked duplicate. It doesn't need more answers.
@T.J.Crowder cool down please. I didn't know the exact key words to search for this issue, so calm down man. feel free to down vote it to to close it. And Thanks Alex for the answer.
@T.J.Crowder I just missed how to search for it. You notice that I have a reputation of 2,404, so I am not a newbie. Thanks for the duplicated possible questions, I am checking them. But I thought you are the one who down voted the question.
@alim1990 - Nope, not me. :-) It's often that way, one person comments and another downvotes. My bar for downvoting is fairly high.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.