Javascript:如何获取多个重复记录的唯一ID

时间:2016-07-12 18:08:02

标签: javascript object duplicates distinct-values

说我们有一个对象:

   var db = [
        {Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" },
        {Id: "202", Player: "Sam",price: "4.22", loc: "PA" },
        {Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" },
        {Id: "204", Player: "Bill",price: "3.22", loc: "TX" },
        {Id: "205" ,Player: "Dave",price: "3.99", loc: "WA" },
        {Id: "206" ,Player: "Dave",price: "3.99", loc: "WI" },
];
202,203,205,206对于玩家和价格具有相似的值,但我只需要一个id用于相似的值,即输出应为202,205。

3 个答案:

答案 0 :(得分:1)

您可以先使用reduce()返回包含每个Player|price组合计数的对象。然后,您可以使用另一个减少,并检查Player|price数量是否> 1。如果是,则将对象id添加到数组。

var db = [
   {Id: "201" ,Player: "Jon",price: "3.99", loc: "NJ" },
   {Id: "202", Player: "Sam",price: "4.22", loc: "PA" },
   {Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" },
   {Id: "204", Player: "Bill",price: "3.22", loc: "TX" },
   {Id: "205" ,Player: "Dave",price: "3.99", loc: "WA" },
   {Id: "206" ,Player: "Dave",price: "3.99", loc: "WI" },
];

var obj = db.reduce(function(o, e) {
  o[e.Player + '|' + e.price] = (o[e.Player + '|' + e.price] || 0) + 1;
    return o;
}, {});

var result = db.reduce(function(r, e) {
  if(obj[e.Player + '|' + e.price] > 1) r.push(e.Id);
    return r;
}, []);

console.log(result)

答案 1 :(得分:1)

var result = []; 

db.forEach(function(item, index){  
   db.forEach(function(item2, index2){ 
      if (index == index2) return;
      if (item.Player == item2.Player && item.price == item2.price) {   
         if(result.indexOf(item.Id) < 0){  
           result.push(item.Id);
         }
         if(result.indexOf(item2.Id) < 0){
           result.push(item2.Id);
         }
      }
   });
});

console.log(result); // [202,203,205,206]

我并不是说这是有史以来最正确的决定,但它足够有效且可以理解。您可以通过以下评论自行检查:

https://codepen.io/anon/pen/vKWZKx

答案 2 :(得分:0)

您可以通过简单循环获取ID。

var db = [
        {Id: "201" , Player: "Jon",price: "3.99", loc: "NJ" },
        {Id: "202", Player: "Sam",price: "4.22", loc: "PA" },
        {Id: "203" ,Player: "Sam",price: "4.22", loc: "NY" },
        {Id: "204", Player: "Bill",price: "3.22", loc: "TX" },
        {Id: "205" ,Player: "Dave",price: "3.99", loc: "WA" },
        {Id: "206" ,Player: "Dave",price: "3.99", loc: "WI" },
];

for(var i = 0; i < db.length; i++){
  var obj = db[i];
  console.log('Id: ', obj.Id);
}