DEV Community

Reaper
Reaper

Posted on • Edited on

Create a unique array using the object params as the identifier.

I wrote this as a comment and thought it'd help out a few of the devs that search this quite often.

const sourceArray = [{id:1},{id:2},{id:3}]
const uniqueArray = []

sourceArray.reduce((acc,item)=>{
    if(!acc.has(item.id)){
        uniqueArray.push(item);
        acc.add(item.id);
    }

    return acc;
},new Set());

Enter fullscreen mode Exit fullscreen mode

Explanation

If you need an explanation, here goes.

There's a sourceArray which may or maynot contain objects and if it does contain objects, let's assume it has a id key that I need to consider for the uniqueness.

Now, reduce provides a way for us to accumulate over a temporary variable that looses scope as soon as the reduce function completes execution so we are going to use that to create a set that holds the property that we are to consider for the uniqueness.

Observe the last line of the snippet, we have a new Set() , sets are basically a collection of unique symbols, in our case it's going to be an id.

The Algo

We are going over each item of the array, checking if the id of it already exists in the set, if it does then we just continue and if it doesn't then we add it to a new array name uniqueArray.

It's simple, works on more than just a simple array of numbers and is faster than using a Map or a [] in the reduce function.

Top comments (0)