JavaScript - Remove duplicates from an array and return an array containing the duplicates and another array containing all other items
P粉986937457
P粉986937457 2023-08-17 22:28:55
0
1
485
<p>I want to run a filter or reduce operation on an array and remove all duplicates in the array based on the 'name' attribute like in this example. The examples I've seen are iterating through the array and keeping one of the duplicates, but in my case I need to separate them and return the duplicates to the user in an array to correct the data, and process the other remaining items. I've given an example array and expected result array below. If anyone could give me an example of how to do this I would be very grateful! Thanks! </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>This will give me the following two arrays: </p> <pre class="brush:php;toolbar:false;">[ { id:1, name: "John", address="123 street"},, { id:3, name: "John", address="674 street"}, ] and [ { 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

reply all(1)
P粉322319601

try it

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);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!