Skip to content

JavaScript: check if duplicate key values exist in array of objects and remove all but most recently added object having that key value

I’m trying to figure out how to check for duplicate values of keys between objects in the same array, then only keep the most recently added object having that value.

For example, I have an array of objects I’m trying to filter duplicates of m_id out of, like so:

arr = [
  {id: "id-1", m_id: "1", color: "blue"},
  {id: "id-2", m_id: "1", color: "green"},
  {id: "id-3", m_id: "2", color: "red"},
  {id: "id-4", m_id: "2", color: "yellow"},
  {id: "id-5", m_id: "5", color: "purple"}
]

The desired result from the above example array of objects would be:

arr = [
  {id: "id-2", m_id: "1", color: "green"},
  {id: "id-4", m_id: "2", color: "yellow"},
  {id: "id-5", m_id: "5", color: "purple"}
]

As you can see, I have a simple id string value that gets incremented for the collection by design. What I’m trying to do is find if a duplicate m_id value exists between any two objects in the array, then remove the object(s) having the lower of the two ids. By lower, in this case, I mean non-numeric boolean comparison of the string ids (e.g., Boolean("id-1" < "id-2") returns true).

I’ve tried using Array.prototype.filter() in combination with Array.prototype.some() in numerous floundering permutations, but I keep running into trouble when I’m looking to compare key values of object elements in the same array inside my filter when the overall collection is not in scope. I’m at a loss so far in getting the results I need.

Answer

You can turn it into a Map indexed by m_id, then take the map’s values:

const map = new Map(
  arr.map(obj => [obj.m_id, obj])
);
const deduplicatedArr = [...map.values()];

(you might be able to use an object here, but only if the respective order of non-duplicate IDs doesn’t need to be preserved – since the IDs are numeric, they’ll be iterated over in ascending numeric order if they were properties of an object)