skip to Main Content

i have an array like this.

0: {id: 4, country: Japan},
1: {id: 5, country: Korea},
2: {id: 6, country: Philippines},
3: {id: 6, country: Philippines} 

How can I remove both record with the same id? so the returned data should look like this.

0: {id: 4, country: Japan},
1: {id: 5, country: Korea}

How can i fix this? I tried the methods described in a specific topic here but it didn’t work

3

Answers


  1. const data = [
        {id: 4, country: 'Japan'},
        {id: 5, country: 'Korea'},
        {id: 6, country: 'Philippines'},
        {id: 6, country: 'Philippines'}
    ];
    
    const duplicates = data.filter((obj, index, arr) => {
      return arr.map(mapObj => mapObj.id).indexOf(obj.id) !== index;
    });
    
    const uniqueData = data.filter((obj, index, arr) => {
      return arr.map(mapObj => mapObj.id).indexOf(obj.id) === index;
    });
    
    console.log("Duplicates:", duplicates);
    console.log("Unique data:", uniqueData);
    
    Login or Signup to reply.
  2. For each element of the array if there are elements equal to it, it is marked as "to be removed" and meanwhile the equal elements are removed. The i element is removed at the end.

    function removeDuplicates(a){
      for(let i = 0 ; i < a.length ; i++){
        let toRemove = false;
        for(let j = 0; j < a.length ; j++){
          if(i != j && a[i].id == a[j].id){
            toRemove = true;
            a.splice(j,1);
          }
        }
        if(toRemove) a.splice(i,1)
      }
      return a;
    }
    
    Login or Signup to reply.
  3. this is another way to do that

    let data = 
    [
    {id: 4, country: "Japan"},
    {id: 5, country: "Korea"},
    {id: 6, country: "Philippines"},
    {id: 6, country: "Philippines"}
    
    ]; 
    
    data.map((s, i) => {
     if (i>0 &&s.id != data[i- 1].id) {
      return s;
     }else{
      delete data[i- 1];
     }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search