Skip to content

Find unique values in a JavaScript array by property

var array = [
  {"name": "64615", "age": "Z91.81", "code": "HISTORY OF FALLING"}, 
  {"name": "97110", "age": "Z91.82", "code": "HISTORY OF FALLING"}, 
  {"name": "20305", "age": "Z91.81", "code": "HISTORY OF FALLING"}
];  

const key = 'age';

console.log(array.map( o => o.age).filter( (v,i,a) => a.indexOf(v)===i));

// ["Z91.81", "Z91.82"] 

To return the whole object of unique values, try the following code snippet.

const arrayUniqueByKey = [...new Map(array.map(
    item =>  [item[key], item])
    ).values()];

console.log(arrayUniqueByKey);

[LOG]: [{
  "name": "20305",
  "age": "Z91.81",
  "code": "HISTORY OF FALLING"
}, {
  "name": "97110",
  "age": "Z91.82",
  "code": "HISTORY OF FALLING"
}] 
See also  Reverse String II - Leetcode Challenge - Python Solution

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.