Home > Mobile >  How to get unique values from an array of objects in JavaScript, but filtered by certain value
How to get unique values from an array of objects in JavaScript, but filtered by certain value

Time:08-14

I would like to extend the question that has been asked some time ago: How to get distinct values from an array of objects in JavaScript?

my case is very similar: I have the following:

var array = 
    [
        {"name":"Doctor", "age":17}, 
        {"name":"Doctor", "age":17},
        {"name":"Doctor", "age":18},
        {"name":"Nurse", "age":17}, 
        {"name":"Nurse", "age": 35}
        {"name":"Nurse", "age": 35}
    ]

What is the best way to be able to get an array of all of the distinct ages, but for chosen speciality such that I get an result array of:

filter by doctor parameter: [17, 18]

filter by nurse parameter: [17, 35]

CodePudding user response:

Use array functions

const array = [{
    "name": "Doctor",
    "age": 17
  },
  {
    "name": "Doctor",
    "age": 18
  },
  {
    "name": "Nurse",
    "age": 17
  },
  {
    "name": "Nurse",
    "age": 35
  }
]

console.log(getUniqueAges(array, 'Doctor'))
console.log(getUniqueAges(array, 'Nurse'))

function getUniqueAges(data, name) {
  return [...new Set(data
    .filter(datum => datum.name === name)
    .map(datum => datum.age))]
}

CodePudding user response:

just like in the answer you linked, but you filter (the example below is filtered by name==="doctor) the array before you pass it to the Set:

const data =     [
    {"name":"Doctor", "age":17}, 
    {"name":"Doctor", "age":18},
    {"name":"Nurse", "age":17}, 
    {"name":"Nurse", "age": 35}
];
const unique = [...new Set(data.filter(item => item.name === "doctor").map(item => item.age))]; // [ '17', '18']
  • Related