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" } ]
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.
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.
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.
7 ways to remove duplicates from an array in JavaScript.
var unique = arr.filter(function(elem, index, self) {
return index === self.indexOf(elem);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With