I wanted to run a filter or reduce operation on an array and remove all duplicate items from the array based on an attribute like 'name' in this example. The examples I see are iterating through the array and keeping one of the duplicate items but in my case I need to separate them and return the duplicate items in an array to the user to correct the data and take the other remaining items and process them. I am giving an example below of an example array and the desired result arrays. If anyone can give me an example of how to do this I would really appreciate it! Thank you!

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"}
];

which should give me the following two arrays:

[
{ 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"}
]

1

There are 1 best solutions below

0
Simba On

Try this

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("Non-Unique Customers:", nonUniqueCustomers);
console.log("Unique Customers:", uniqueCustomers);