JS - 数组中的重复元素

时间:2016-05-27 02:20:31

标签: javascript angularjs

好吧,我无法解释我正在尝试做什么。但我可以解释一下白衣代码。

我有这个数组:

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

数组包含2个重复的元素,我想要一个只显示元素重复的函数

当你应用这个函数时,这将是数组的结果

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

3 个答案:

答案 0 :(得分:2)

您可以使用javascript filter函数以老式方式实现它。

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

答案 1 :(得分:0)

你使用lodash库,它给你很多数组/对象&字符串函数。

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

上面的代码将检查每个对象的深度相等性并创建一个唯一的数组。
文档:lodash uniqWith

答案 2 :(得分:0)

非常简单的方法是使用下划线

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

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

使用独特的成就