P粉3223196012023-08-18 14:18:08
嘗試一下
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);