Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove 'duplicate' objects from array by comparing sub properties (typescript)

I receive an array of complex objects from the server. I would like to filter the original array to get a new array with unique objects by a sub-property of an each object, i.e :

let arr1 = originalArray;
let arr2 = originalArray.filter((ele, idx, arr) => ....

Now for example, arr1 consists of 3 objects:

firstObj = {
    id: 0,
    Details:
        {
            License: 123456
        },
    name: 'abc'
};
secondObj = {
    id: 1,
    Details:
        {
            License: 131313
        },
    name: 'xcd'
};
thirdObj = {
    id: 2,
    Details:
        {
            License: 123456
        },
    name: 'bcd'
};

So, I want to filter the array so that the newly returned array will consist of only two objects where the 'License' property will be unique, that is, one of the objects with the same 'License' will be removed. Thanks.

like image 637
dextercom Avatar asked Jun 03 '18 11:06

dextercom


People also ask

How do you remove duplicate objects from an array of objects?

To remove the duplicates from an array of objects:Use the Array. filter() method to filter the array of objects. Only include objects with unique IDs in the new array.

How do you remove duplicates from an array of arrays?

To remove duplicates from an array: First, convert an array of duplicates to a Set . The new Set will implicitly remove duplicate elements. Then, convert the set back to an array.


1 Answers

You can use array.reduce to loop through source array and add items to result if it does not contain same Details.License

let result = [firstObj, secondObj, thirdObj].reduce((arr, item) => {
    let exists = !!arr.find(x => x.Details.License === item.Details.License);
    if(!exists){
        arr.push(item);
    }
    return arr;
}, []);
like image 92
mickl Avatar answered Sep 28 '22 00:09

mickl