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

3 Answers 3

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"}]
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

2 Comments

Lodash and underscore are different libraries.
@zerkms Thanks for your input. I thought both are different only by name but does the same job with reference to functionality.

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.