Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove duplicate objects from JavaScript array

This is my code

var studentsList = [
    {"Id": "101", "name": "siva"},
    {"Id": "101", "name": "siva"},
    {"Id": "102", "name": "hari"},
    {"Id": "103", "name": "rajesh"},
    {"Id": "103", "name": "rajesh"},
    {"Id": "104", "name": "ramesh"},
];

function arrUnique(arr) {
    var cleaned = [];
    studentsList.forEach(function(itm) {
        var unique = true;
        cleaned.forEach(function(itm2) {
            if (_.isEqual(itm, itm2)) unique = false;
        });
        if (unique)  cleaned.push(itm);
    });
    return cleaned;
}

var uniqueStandards = arrUnique(studentsList);

document.body.innerHTML = '<pre>' + JSON.stringify(uniqueStandards, null, 4) + '</pre>';

OutPut

[
{
    "Id": "101",
    "name": "siva"
},
{
    "Id": "102",
    "name": "hari"
},
{
    "Id": "103",
    "name": "rajesh"
},
{
    "Id": "104",
    "name": "ramesh"
}
]

In the above code I got unique objects from the JavaScript array, but i want to remove duplicate objects. So I want to get without duplicate objects from the array, the output like [ { "Id": "102", "name": "hari" }, { "Id": "104", "name": "ramesh" } ]

like image 785
durga siva kishore mopuru Avatar asked Sep 07 '15 07:09

durga siva kishore mopuru


People also ask

How do you find duplicate objects in an array?

Using the indexOf() method In this method, what we do is that we compare the index of all the items of an array with the index of the first time that number occurs. If they don't match, that implies that the element is a duplicate. All such elements are returned in a separate array using the filter() method.

How do you remove duplicates in array of objects in JS?

We can also use a Set object to remove all duplicates from an array of objects. Copied! const arr = [ {id: 1, name: 'Tom'}, {id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}, {id: 2, name: 'Nick'}, ]; const uniqueIds = new Set(); const unique = arr.

How can I remove the duplicate items in an array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays.sort(arr) method.

How many ways can we remove duplicates from array in JavaScript?

7 ways to remove duplicates from an array in JavaScript.


1 Answers

var unique = arr.filter(function(elem, index, self) {
    return index === self.indexOf(elem);
})
like image 188
Mehdi Daustany Avatar answered Oct 12 '22 00:10

Mehdi Daustany