【问题标题】:How to get the duplicates objects in an array?如何获取数组中的重复对象?
【发布时间】:2022-01-21 10:24:16
【问题描述】:

我有一个这样的数组:

    var clients=[{"id":1,"name":"john","age":20},
{"id":3,"name":"dean","age":23},
{"id":12,"name":"harry","age":14},
{"id":1,"name":"sam","age":22},
{"id":13,"name":"Bolivia","age":16},
{"id":7,"name":"sabi","age":60},
{"id":7,"name":"sahra","age":40},
{"id":4,"name":"natie","age":53},{"id":7,"name":"many","age":22}]

我想找到重复的对象并像这样对它们进行聚类:

 [
       {
       "id":1,
        "clients":[
                    {"id":1,"name":"john","age":20},
                    {"id":1,"name":"sam","age":22}
                   ]
       },
     {
       "id":7,
       "clients":[
                   {"id":7,"name":"sabi","age":60},
                   {"id":7,"name":"sahra","age":40},
                   {"id":7,"name":"many","age":22}
                  ]
      }
    ]

我可以像这样使用 filter() 做到这一点吗:clients.reduce(//code hier)

【问题讨论】:

  • 研究reduce 方法,想想你可以用聚合值做什么,这些聚合值不仅仅是总和等,而是其他数组或对象......
  • 为什么不能“允许定义新数组”?

标签: javascript arrays reduce


【解决方案1】:

reduce() 就是为此量身定做的。当你想对一个数组进行聚合并得到一个计算结果时,你应该使用reduce()

find() 是另一种数组方法,它有助于根据条件(这里是 id 属性的匹配)查找数组元素。

var clients=[{"id":1,"name":"john","age":20},
{"id":3,"name":"dean","age":23},
{"id":12,"name":"harry","age":14},
{"id":1,"name":"sam","age":22},
{"id":13,"name":"Bolivia","age":16},
{"id":7,"name":"sabi","age":60},
{"id":7,"name":"sahra","age":40},
{"id":4,"name":"natie","age":53},{"id":7,"name":"many","age":22}]


let ans = clients.reduce((agg,x,index) => {
 let findI = agg.find( a => 
  a.id === x.id
 );
 if(findI) findI.clients.push(x);
 else {
   agg.push({
     id : x.id,
     clients : [x] 
   });
 }
 return agg;
},[]);

console.log(ans);

【讨论】:

  • 这可能会完成这项工作,但我发现它非常难以理解。祝继承此代码并试图弄清楚它的作用的可怜的开发人员好运(这很可能在 6 个月内成为 OP)。
【解决方案2】:

最简单的解决方案是遍历clients 并检查具有相同id 的现有对象。如果是,推送到clients 数组。否则,只需创建一个。

var clients = [{ "id": 1, "name": "john", "age": 20 },
{ "id": 3, "name": "dean", "age": 23 },
{ "id": 12, "name": "harry", "age": 14 },
{ "id": 1, "name": "sam", "age": 22 },
{ "id": 13, "name": "olivia", "age": 16 },
{ "id": 7, "name": "sabi", "age": 60 },
{ "id": 7, "name": "sahra", "age": 40 },
{ "id": 4, "name": "natie", "age": 53 }, { "id": 7, "name": "kany", "age": 22 }]

const groups = [];

for (let client of clients) {
  const existingGroup = groups.find(group => group.id == client.id)
  if (existingGroup)
    existingGroup.clients.push(client);
  else {
    groups.push({ id: client.id, clients: [client] });
  }
}

console.log(groups);

您可以使用刚刚用于此的临时对象重新分配原始对象,并继续您的业务逻辑,我相信这就是您正在寻找的。​​p>

【讨论】:

    猜你喜欢
    • 2021-07-20
    • 2019-01-06
    • 1970-01-01
    • 2016-12-08
    • 1970-01-01
    • 2021-03-23
    • 2019-04-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多