get all unique keys from array js code example

Example 1: javascript unique array of objects by property

const array =
  [
    { "name": "Joe", "age": 17 },
    { "name": "Bob", "age": 17 },
    { "name": "Carl", "age": 35 }
  ]

function uniqueByKey(array, key) {
  return [...new Map(array.map((x) => [x[key], x])).values()];
}

console.log(uniqueByKey(array, 'age'));

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']