在Javascript中从Array中删除重复的元素

时间:2016-11-08 08:49:36

标签: javascript arrays duplicates

我有一个带有obejcts电子邮件和Id的数组,所以我想要删除具有类似ID的重复元素。

示例:

var newarray=[
    {
        Email:"test1@gmail.com",
        ID:"A"
    },
    {
        Email:"test2@gmail.com",
        ID:"B"
    },
    {
        Email:"test3@gmail.com",
        ID:"A"
    },
    {
        Email:"test4@gmail.com",
        ID:"C"
    },
    {
        Email:"test4@gmail.com",
        ID:"C"
    }
];

现在我需要删除ID为常见的重复元素。我希望最终的数组是

var FinalArray=[
    {
        Email:"test1@gmail.com",
        ID:"A"
    },
    {
        Email:"test2@gmail.com",
        ID:"B"
    },  
    {
        Email:"test5@gmail.com",
        ID:"C"
    }
];

4 个答案:

答案 0 :(得分:5)

使用Array.prototype.filter过滤掉元素并使用temp数组检查重复项



var newarray = [{
  Email: "test1@gmail.com",
  ID: "A"
}, {
  Email: "test2@gmail.com",
  ID: "B"
}, {
  Email: "test3@gmail.com",
  ID: "A"
}, {
  Email: "test4@gmail.com",
  ID: "C"
}, {
  Email: "test5@gmail.com",
  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);




答案 1 :(得分:4)

您可以使用哈希表过滤它。

var newarray = [{ Email: "test1@gmail.com", ID: "A" }, { Email: "test2@gmail.com", ID: "B" }, { Email: "test3@gmail.com", ID: "A" }, { Email: "test4@gmail.com", ID: "C" }, { Email: "test5@gmail.com", ID: "C" }],
    filtered = newarray.filter(function (a) {
        if (!this[a.ID]) {
            this[a.ID] = true;
            return true;
        }
    }, Object.create(null));

console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }

ES6与Set

var newarray = [{ Email: "test1@gmail.com", ID: "A" }, { Email: "test2@gmail.com", ID: "B" }, { Email: "test3@gmail.com", ID: "A" }, { Email: "test4@gmail.com", ID: "C" }, { Email: "test5@gmail.com", ID: "C" }],
    filtered = newarray.filter((s => a => !s.has(a.ID) && s.add(a.ID))(new Set));

console.log(filtered);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 2 :(得分:2)

如果您可以使用下划线或lodash等Javascript库,我建议您查看其库中的_.uniq函数。来自lodash:

_.uniq(array, [isSorted=false], [callback=_.identity], [thisArg])

在这里你必须使用如下,

var non_duplidated_data = _.uniq(newarray, 'ID'); 

答案 3 :(得分:1)

使用Array.prototype.reduce和哈希表的另一种解决方案 - 请参阅下面的演示:

var newarray=[ { Email:"test1@gmail.com", ID:"A" }, { Email:"test2@gmail.com", ID:"B" }, { Email:"test3@gmail.com", ID:"A" }, { Email:"test4@gmail.com", ID:"C" }, { Email:"test5@gmail.com", ID:"C" } ];

var result = newarray.reduce(function(hash){
  return function(prev,curr){
     !hash[curr.ID] && (hash[curr.ID]=prev.push(curr));
     return prev;
  };
}(Object.create(null)),[]);

console.log(result);
.as-console-wrapper{top:0;max-height:100%!important;}

相关问题