Luis Alvarez
Luis Alvarez

Reputation: 99

JS - Duplicate Elements in the Array

Okay i can't explain what i'm trying to do . but i can explain whit code.

i have this array :

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}]

the array contains 2 elements duplicated , I want a function that shows me only once an element duplicate

when you apply the function this will be the result of the array

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"}]

Upvotes: 2

Views: 136

Answers (3)

Jagajit Prusty
Jagajit Prusty

Reputation: 2110

you use lodash library which gives you many array/object & string functions.

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}]

_.uniqWith(array, _.isEqual);//[{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"}]

The above code will check deep equality of each object and create a unique array.
Docs : lodash uniqWith

Upvotes: 0

Gayathri Mohan
Gayathri Mohan

Reputation: 2962

the very simple way is use the underscore

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}]  

array  = _.uniq(array , false, function(p) {
                 return p.name;
            });

use the unique to achive

Upvotes: 0

choz
choz

Reputation: 17898

You can achieve it with javascript filter function in old fashioned way.

var array = [{name:"John",lastname:"Doe"},{name:"Alex",lastname:"Bill"},{name:"John",lastname:"Doe"}]
var names = [];

array = array.filter(function (person) {
   var fn = person.name + '-' + person.lastname;
   if (names.indexOf(fn) !== -1) {
      return false;
   }
   else {
      names.push(fn);
      return true;
   }
});

console.log(array); 
// [{"name":"John","lastname":"Doe"},{"name":"Alex","lastname":"Bill"}]

Upvotes: 2

Related Questions