JavaScript: Merge Duplicate Objects in an Array of Objects

Miroslav Maksimovic
The Startup
Published in
2 min readDec 19, 2019

Sometimes in your every day of programming you get an array of objects which are not unique 😰.

You have an array of objects where some of them are duplicates but with different object properties, and you want to get only one object with all of those properties.

In JavaScript:

  • Objects are used for storing keyed collections.
  • Arrays are used for storing ordered collections.

Let’s see the actual code problem:

[
{
label: "Book1",
data: "US edition"
},
{
label: "Book1",
title: "UK edition"
},
{
label: "Book1",
date: "12.2.2020"
},
{
label: "Book2",
data: "CAN edition"
},
{
label: "Book2",
title: "test edition"
}
];

You want to see this kind of data:

[
{
label: "Book1",
data: "US edition",
title: "UK edition",
date: "12.2.2020",
etc: "etc..."
},
{
label: "Book2",
data: "CAN edition",
title: "test edition"
}
];

Firstly let’s see which data structure we can use to help us achieve this approach, e.g. we can use Map 🤩.

Map is a collection of keyed data items, just like an Object. But the main difference is that Map allows keys of any type.

If your object property is of any kind it will work with Map :D.

First, consider making an interface for your object:

class: IBook {
label: string;
data: string;
title: string;
date: Date;
etc: Etc;
}

The javascript function will be like this:

We simply looped over each item of the original array and check if we already have key-value pairs inside Map and append to the existing pair, if not creating a new one with the values provided.

The function will work with any type of object in the array.

Calling this function is as simple as :

mergeObjectsInUnique(myArrayWithDuplicates, 'propertyThatIWantToGroupBy');

Hope you like it, clap for making it visible to a wider audience 🥳 and help spread the word 😎.

--

--

Miroslav Maksimovic
The Startup

Software Engineer, passionate knowledge transferer, writer for The Startup, largest publication @Medium with over 700k followers