JavaScript - Remove duplicates from an array and return an array containing the duplicates and another array containing all other items
P粉986937457
2023-08-17 22:28:55
<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>
try it