JavaScript - 從陣列中刪除重複項,並傳回一個包含重複項的陣列和另一個包含所有其他項目的陣列
P粉986937457
P粉986937457 2023-08-17 22:28:55
0
1
513
<p>我想在一個數組上運行一個過濾器或縮減操作,並根據像這個例子中的'name'屬性刪除數組中的所有重複項。我看到的例子是遍歷數組並保留其中一個重複項,但在我的情況下,我需要將它們分開,並將重複項以數組的形式返回給用戶以更正數據,並處理其他剩餘項。我在下面給出了一個示例數組和期望的結果數組。如果有人能給我一個如何做到這一點的例子,我將非常感激!謝謝! </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>這將給我以下兩個陣列:</p> <pre class="brush:php;toolbar:false;">[ { id:1, name: "John", address="123 street"},, { id:3, name: "John", address="674 street"}, ] 和 [ { 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

全部回覆(1)
P粉322319601

嘗試一下

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);
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板