DEV Community

Reaper
Reaper

Posted on • Edited on

3 3

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.

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay