1

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

4 Answers 4

1

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)

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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);

Comments

0

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);  
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.