Javascript Unique Objects By Key

Suppose you have an array of objects in javascript:

[{id: "a", foo: "bar1"}, {id: "b", foo: "bar2"}, {id: "a", foo: "bar3"}]

In the above contrived example 2 of the 3 objects have the same id value of a. We’d like to filter this array so that the result is:

[{id: "a", foo: "bar1"}, {id: "b", foo: "bar2"}]

Javascript doesn’t have a built in unique function like other languages do. But we can use the filter method. The standard filter method we might use would look like this:

const onlyUnique = (value, index, self) => {
    return self.indexOf(value) === index

That function works great on arrays of elements like:

["a", "b", "a"]

We can call:

const u = ["a", "b", "a"].filter(onlyUnique);

The value of u is now assigned the value: ["a", "b"] . That’s great, but it won’t filter on the id key like we need it to do. We can make it work by modifying the onlyUnique function to take into account our keys:

 const onlyUniqueIds = (value, index, self) => {
    const k = =>;
    return self.indexOf(value) === k.indexOf(;

Basically, in the above code, we first isolate the id key into its own array. Then we use the basic onlyUnique code but instead of comparing to the index, we compare it to the index of the in the new k array. Now we can run this code on our objects:

const uniqueObjects = [{id: "a", foo: "bar1"}, {id: "b", foo: "bar2"}].filter(onlyUniqueIds)

Now we have our unique array. Hopefully that helped. It took me a few minutes to figure this out. If there is a better way, I’d love to know about it!

Leave a Reply

Your email address will not be published. Required fields are marked *