Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

222
Visualizações
How to get unique values from an array of objects in JavaScript, but filtered by certain value

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]

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

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))]
}

about 4 years ago · Santiago Trujillo Relatório

0

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']
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda