Reputation: 157
i have a collection with some of duplicate objects , i want filter array and get unique collection this is my array
array=[{id:1,name:'A'},{id:2,name:'B'},{id:3,name:'C'},{id:1,name:'A'},{id:3,name:'C'}];
i want to filter like below
array=[{id:1,name:'A'},{id:2,name:'B'},{id:3,name:'C'}];
var unique = [];
for(let i = 0; i< this.array.length; i++){
if(unique.indexOf(this.array[i].id) === -1){
unique.push(this.array[i].id);
}
}
i tried above and am getting unique values but i want complete object
Upvotes: 1
Views: 1295
Reputation: 1
Replace Id with the respective key of the array.
arrayUnique(array)
{
let result:any=[];
let compare:any=[];
array.forEach((val,ind)=>{
if(!compare.includes(val.id))
{
compare.push(val.id);
result.push(val);
}
});
console.log(result);
}
Upvotes: 0
Reputation: 37775
You can do it with help of reduce
let arr=[{id:1,name:'A'},{id:2,name:'B'},{id:3,name:'C'},{id:1,name:'A'},{id:3,name:'C'}];
let op = Object.values(arr.reduce((o,c)=>{
if(!o[c.id]) o[c.id] = c;
return o; }, {} ))
console.log(op);
Upvotes: 0
Reputation: 1028
I think you are almost there. Just add the object instead of the ID to the array, ie:
unique.push(this.array[i]);
That should do it if I understand your question.
Upvotes: 0
Reputation: 222722
You can do with arrray.filter as follows,
var unique = {}
var array=[{"id":1,"name":'A'},{"id":"2","name":'B'},{"id":3,"name":'C'},{"id":1,"name":'A'},{"id":3,name:'C'}];
var arrFiltered = array.filter(obj => !unique[obj.id] && (unique[obj.id] = true));
console.log(arrFiltered)
Upvotes: 1