Get unique objects from an array

tepexic

Jesús Velázquez

Posted on November 23, 2021

Get unique objects from an array

Suppose you have an array of objects with at least one common property that could be used as an identifier.

This function will allow you to create a new array with unique objects based on the selected property:

function getUniqueElementsFromArray(array, uniqueProperty) {
  const result = [];
  // The map will help us keep a record of the objects
  const map = new Map();
  array.forEach((item, i) => {
    if (!map.has(item[uniqueProperty])) {
      // New element, push it into results
      map.set(item[uniqueProperty], true); // you can set any value, we just need it to be in the Map
      // save unique object
      result.push(item);
      }
    });
  return result;
};
Enter fullscreen mode Exit fullscreen mode

Example:
Let's say we have an array:

const sample = [
  {name: 'a', points: 20, game: 1},
  {name: 'e', points: 5, game: 3},
  {name: 'a', points: 15, game: 3},
  {name: 'i', points: 5, game: 3},
  {name: 'e', points: 50, game: 1},
  {name: 'a', points: 0, game: 5},
  {name: 'o', points: 100, game: 2},
  {name: 'e', points: 20, game: 2},
  {name: 'u', points: 20, game: 1},
  {name: 'i', points: 50, game: 2},
]
Enter fullscreen mode Exit fullscreen mode

We can use the property 'name' as identifier

console.log(getUniqueElementsFromArray(sample, 'name'))
Enter fullscreen mode Exit fullscreen mode

And the result will yield:

[
  { name: 'a', points: 20, game: 1 },
  { name: 'e', points: 5, game: 3 },
  { name: 'i', points: 5, game: 3 },
  { name: 'o', points: 100, game: 2 },
  { name: 'u', points: 20, game: 1 }
]
Enter fullscreen mode Exit fullscreen mode

Adding here a typescript version:

export const getUniqueItems = (array: any[], uniqueProperty: string): any => {
  const result: any[] = []
  const map = new Map()
  array.forEach((item) => {
    if (!map.has(item[uniqueProperty])) {
      map.set(item[uniqueProperty], true)
      result.push(item)
    }
  })
  return result
}
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
tepexic
Jesús Velázquez

Posted on November 23, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Get unique objects from an array
javascript Get unique objects from an array

November 23, 2021

JS array vs object vs map
javascript JS array vs object vs map

August 4, 2020