问题
I have array with obejcts email and Id so I want delete duplicate elements who have similar ID's.
Example:
var newarray=[
{
Email:"test1@gmail.com",
ID:"A"
},
{
Email:"test2@gmail.com",
ID:"B"
},
{
Email:"test3@gmail.com",
ID:"A"
},
{
Email:"test4@gmail.com",
ID:"C"
},
{
Email:"test4@gmail.com",
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:"test1@gmail.com",
ID:"A"
},
{
Email:"test2@gmail.com",
ID:"B"
},
{
Email:"test5@gmail.com",
ID:"C"
}
];
回答1:
Use Array.prototype.filter to filter out the elements and to keep a check of duplicates use a temp
array
var newarray = [{
Email: "test1@gmail.com",
ID: "A"
}, {
Email: "test2@gmail.com",
ID: "B"
}, {
Email: "test3@gmail.com",
ID: "A"
}, {
Email: "test4@gmail.com",
ID: "C"
}, {
Email: "test5@gmail.com",
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);
回答2:
You could filter it with a hash table.
var newarray = [{ Email: "test1@gmail.com", ID: "A" }, { Email: "test2@gmail.com", ID: "B" }, { Email: "test3@gmail.com", ID: "A" }, { Email: "test4@gmail.com", ID: "C" }, { Email: "test5@gmail.com", ID: "C" }],
filtered = newarray.filter(function (a) {
if (!this[a.ID]) {
this[a.ID] = true;
return true;
}
}, Object.create(null));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
ES6 with Set
var newarray = [{ Email: "test1@gmail.com", ID: "A" }, { Email: "test2@gmail.com", ID: "B" }, { Email: "test3@gmail.com", ID: "A" }, { Email: "test4@gmail.com", ID: "C" }, { Email: "test5@gmail.com", ID: "C" }],
filtered = newarray.filter((s => a => !s.has(a.ID) && s.add(a.ID))(new Set));
console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }
回答3:
If you can use Javascript libraries such as underscore or lodash, I recommend having a look at _.uniq function in their libraries. From lodash:
_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])
Here you have to use like below,
var non_duplidated_data = _.uniq(newarray, 'ID');
回答4:
Another solution using Array.prototype.reduce
and a hash table - see demo below:
var newarray=[ { Email:"test1@gmail.com", ID:"A" }, { Email:"test2@gmail.com", ID:"B" }, { Email:"test3@gmail.com", ID:"A" }, { Email:"test4@gmail.com", ID:"C" }, { Email:"test5@gmail.com", ID:"C" } ];
var result = newarray.reduce(function(hash){
return function(prev,curr){
!hash[curr.ID] && (hash[curr.ID]=prev.push(curr));
return prev;
};
}(Object.create(null)),[]);
console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}
来源:https://stackoverflow.com/questions/40482541/delete-duplicate-elements-from-array-in-javascript