Skip to content

Modern Unique Array

get distinct values from an array of objects in JavaScript with modern solution

Afif Abdillah Jusuf

Created by / Afif Abdillah Jusuf

JAVASCRIPT
// get unique list from array of object
const data = [
  { group: 'A', name: 'SD' }, 
  { group: 'B', name: 'FI' }, 
  { group: 'A', name: 'MM' },
  { group: 'B', name: 'CO'}
];
const unique = [...new Set(data.map(item => item.group))]; // [ 'A', 'B']

// get unique item of object from array of object
// For those who want to return object with all properties unique by key
const array = [
  { name: "Joe", age: 17 },
  { name: "Bob", age: 17 },
  { name: "Carl", age: 35 },
];
const key = "age";
const arrayUniqueByKey = [
  ...new Map(array.map((item) => [item[key], item])).values(),
];
/*OUTPUT
  [
    { "name": "Bob", "age": 17 },
    { "name": "Carl", "age": 35 }
  ]
*/