Delete duplicate elements from Array in Javascript -
this question has answer here:
- how distinct values array of objects in javascript? 23 answers
- unique values in array 50 answers
i have array obejcts email , id want delete duplicate elements 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 need delete duplicate elements have id's common.in sence expecting final array is
var finalarray=[ { email:"test1@gmail.com", id:"a" }, { email:"test2@gmail.com", id:"b" }, { email:"test5@gmail.com", id:"c" } ];
use array.prototype.filter filter out elements , keep check of duplicates use 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 keep track of duplicates var dups = []; var arr = newarray.filter(function(el) { // if not duplicate, return true if (dups.indexof(el.id) == -1) { dups.push(el.id); return true; } return false; }); console.log(arr);
Comments
Post a Comment