0

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

2
  • 1
    With questions like this, there are lots of possible approaches - including basic brute force approaches. This Q&A site all works better if you show us what you tried and explain what problems you ran into with that approach or where you got stuck. This isn't supposed to just be a code writing site where we just write the code for you. We're here to help you solve a specific problem in your existing coding attempt. Commented Aug 17, 2023 at 2:15
  • 1
    Does this answer your question? How can I check if the array of objects have duplicate property values?, Get list of duplicate objects in an array of objects Commented Aug 17, 2023 at 2:15

1 Answer 1

0

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);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.