get distinct values from array of objects javascript code example

Example 1: filter array with unique objects javascript

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()];

console.log(arrayUniqueByKey);

   /*OUTPUT
       [
        { "name": "Bob", "age": 17 },
        { "name": "Carl", "age": 35 }
       ]
   */

 // Note: this will pick the last duplicated item in the list.

Example 2: javascript get distinct values from array

const categories = ['General', 'Exotic', 'Extreme', 'Extreme', 'General' ,'Water', 'Extreme']
.filter((value, index, categoryArray) => categoryArray.indexOf(value) === index);

This will return an array that has the unique category names
['General', 'Exotic', 'Extreme', 'Water']

Example 3: javascript get unique values from key

const unique = [...new Set(array.map(item => item.age))];

Example 4: Return Distinct Array Object

const array = [    { id: 3, name: 'Central Microscopy', fiscalYear: 2018 },    { id: 5, name: 'Crystallography Facility', fiscalYear: 2018 },    { id: 3, name: 'Central Microscopy', fiscalYear: 2017 },    { id: 5, name: 'Crystallography Facility', fiscalYear: 2017 }  ];const result = [];const map = new Map();for (const item of array) {    if(!map.has(item.id)){        map.set(item.id, true);    // set any value to Map        result.push({            id: item.id,            name: item.name        });    }}console.log(result)