How to remove duplicates from an array of objects in Javascript
To remove duplicates from an array of objects based on a key in the array, you can do this:
<span class="hljs-keyword">const</span> arr = [
{
<span class="hljs-attr">id</span>: <span class="hljs-string">'abc123'</span>,
<span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span>,
},
{
<span class="hljs-attr">id</span>: <span class="hljs-string">'abc123'</span>,
<span class="hljs-attr">hello</span>: <span class="hljs-string">'world'</span>,
}
];
<span class="hljs-keyword">const</span> duplicatesRemoved = [...<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>(arr.<span class="hljs-title function_">map</span>(<span class="hljs-function"><span class="hljs-params">item</span> =></span> [item.<span class="hljs-property">id</span>, item])).<span class="hljs-title function_">values</span>()];
Using a Map is 2x faster than using an Object. You should replace item.id with the key you want to use.
In function form:
<span class="hljs-keyword">function</span> <span class="hljs-title function_">removeDuplicates</span>(<span class="hljs-params">arr = [], key = <span class="hljs-literal">null</span></span>) {
<span class="hljs-keyword">return</span> [...<span class="hljs-keyword">new</span> <span class="hljs-title class_">Map</span>(arr.<span class="hljs-title function_">map</span>(<span class="hljs-function"><span class="hljs-params">item</span> =></span> [item[key], item])).<span class="hljs-title function_">values</span>()];
}
If you pass an invalid key, your array will be 1 in length, since the Map will use undefined as the key.