2

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"}]

3 Answers3

2

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"}]
choz
  • 17,242
  • 4
  • 53
  • 73
0

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

Jagajit Prusty
  • 2,070
  • 2
  • 21
  • 39
0

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

Gayathri Mohan
  • 2,924
  • 4
  • 19
  • 25