Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete duplicate elements from Array in Javascript [duplicate]

I have array with obejcts email and Id so I want delete duplicate elements who have similar ID's.

Example:

var newarray=[
    {
        Email:"[email protected]",
        ID:"A"
    },
    {
        Email:"[email protected]",
        ID:"B"
    },
    {
        Email:"[email protected]",
        ID:"A"
    },
    {
        Email:"[email protected]",
        ID:"C"
    },
    {
        Email:"[email protected]",
        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:"[email protected]",
        ID:"A"
    },
    {
        Email:"[email protected]",
        ID:"B"
    },  
    {
        Email:"[email protected]",
        ID:"C"
    }
];
like image 227
Santosh Khavekar Avatar asked Nov 08 '16 08:11

Santosh Khavekar


1 Answers

Use Array.prototype.filter to filter out the elements and to keep a check of duplicates use a temp array

var newarray = [{
  Email: "[email protected]",
  ID: "A"
}, {
  Email: "[email protected]",
  ID: "B"
}, {
  Email: "[email protected]",
  ID: "A"
}, {
  Email: "[email protected]",
  ID: "C"
}, {
  Email: "[email protected]",
  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);
like image 182
void Avatar answered Sep 30 '22 15:09

void