search

Home  >  Q&A  >  body text

JavaScript - Remove duplicates from an array and return an array containing the duplicates and another array containing all other items

<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粉986937457P粉986937457475 days ago494

reply all(1)I'll reply

  • P粉322319601

    P粉3223196012023-08-18 14:18:08

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

    reply
    0
  • Cancelreply