JavaScript - 从数组中删除重复项,并返回一个包含重复项的数组和另一个包含所有其他项的数组
P粉986937457
P粉986937457 2023-08-17 22:28:55
0
1
512
<p>我想在一个数组上运行一个过滤器或缩减操作,并根据像这个例子中的'name'属性删除数组中的所有重复项。我看到的例子是遍历数组并保留其中一个重复项,但在我的情况下,我需要将它们分开,并将重复项以数组的形式返回给用户以更正数据,并处理其他剩余项。我在下面给出了一个示例数组和期望的结果数组。如果有人能给我一个如何做到这一点的例子,我将非常感激!谢谢!</p> <pre class="brush:php;toolbar:false;">const customers = [ { id:1, name: "John", address="123 street"}, { id:2, name: "Alex", address="456 street"}, { id:3, name: "John", address="674 street"}, { id:4, name: "Stacy", address="534 street"}, { id:5, name: "Blair", address="634 street"} ];</pre> <p>这将给我以下两个数组:</p> <pre class="brush:php;toolbar:false;">[ { id:1, name: "John", address="123 street"},, { id:3, name: "John", address="674 street"}, ] 和 [ { id:2, name: "Alex", address="456 street"}, { id:4, name: "Stacy", address="534 street"}, { id:5, name: "Blair", address="634 street"} ]</pre> <p><br /></p>
P粉986937457
P粉986937457

全部回复(1)
P粉322319601

尝试一下

const customers = [
  { id: 1, name: "John", address: "123 street" },
  { id: 2, name: "Alex", address: "456 street" },
  { id: 3, name: "John", address: "674 street" },
  { id: 4, name: "Stacy", address: "534 street" },
  { id: 5, name: "Blair", address: "634 street" }
];

const nameMap = new Map();
const nonUniqueCustomers = [];
const uniqueCustomers=[];
customers.forEach(customer => {
  if (!nameMap.has(customer.name)) {
    nameMap.set(customer.name, []);
  }
  nameMap.get(customer.name).push(customer);
});

nameMap.forEach(customers => {
  if (customers.length > 1) {
    nonUniqueCustomers.push(...customers);
  }else{
uniqueCustomers.push(...customers)
  
  }
});


console.log("非唯一顾客:", nonUniqueCustomers);
console.log("唯一顾客:", uniqueCustomers);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板