Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
84
rated 0 times [  88] [ 4]  / answers: 1 / hits: 26482  / 8 Years ago, tue, november 8, 2016, 12:00:00

I have array with obejcts email and Id so I want delete duplicate elements who have similar ID's.



Example:



var newarray=[
{
Email:[email protected],
ID:A
},
{
Email:[email protected],
ID:B
},
{
Email:[email protected],
ID:A
},
{
Email:[email protected],
ID:C
},
{
Email:[email protected],
ID:C
}
];


Now I need to delete Duplicate elements which have ID's are common.In the sence I am expecting final Array is



var FinalArray=[
{
Email:[email protected],
ID:A
},
{
Email:[email protected],
ID:B
},
{
Email:[email protected],
ID:C
}
];

More From » arrays

 Answers
118

Use Array.prototype.filter to filter out the elements and to keep a check of duplicates use a temp array





var newarray = [{
Email: [email protected],
ID: A
}, {
Email: [email protected],
ID: B
}, {
Email: [email protected],
ID: A
}, {
Email: [email protected],
ID: C
}, {
Email: [email protected],
ID: C
}];

// Array to keep track of duplicates
var dups = [];
var arr = newarray.filter(function(el) {
// If it is not a duplicate, return true
if (dups.indexOf(el.ID) == -1) {
dups.push(el.ID);
return true;
}

return false;

});

console.log(arr);




[#60148] Saturday, November 5, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kendellc

Total Points: 84
Total Questions: 97
Total Answers: 102

Location: Moldova
Member since Sat, Aug 6, 2022
2 Years ago
;