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

266
Visualizações
Check if value exists in nested array

I am trying to check if a value is present in a nested array. This is what the data I am working with looks like:

[
    {
      name: 'bob',
      occupation: ['Teacher', 'Store Owner'],
    },
    {
      name: 'grace',
      occupation: ['Doctor'],
    },
]

I am trying to see if the occupation value already exists. This is my current code:

const occupationExists = (value) => users.some((user) => user.occupation === value);

I understand that this doesn't work because it isn't accessing the values in the array but how do I go about it? Any help would be appreciated.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You need to check occupation as well with Array#includes.

const occupationExists = value => users.some(user =>
    user.occupation.includes(value)
);
about 4 years ago · Juan Pablo Isaza Relatório

0

This should do the trick, it returns true/false depending on whether the occupation exists or not.

let users = [
    {
      name: 'bob',
      occupation: ['Teacher', 'Store Owner'],
    },
    {
      name: 'grace',
      occupation: ['Doctor'],
    },
]


const occupationExists = (value) => {
    let res = users.filter((user) =>
        user.occupation.indexOf(value) != -1
    )
    return res.length > 0
}
let value = 'Doctor'
console.log(occupationExists(value))
about 4 years ago · Juan Pablo Isaza Relatório

0

Here is the issue with user.occupation === value: user.occupation is an array of string while value is a string, hence you cannot compare the two. You can use Array#includes() as stated by @NinaScholz or you can use another (inner) Array#some() and within it you can compare string to string: job === value.

const users = [{name: 'bob',occupation: ['Teacher', 'Store Owner']}, {name: 'grace',occupation: ['Doctor']}];

//const occupationExists = value => users.some(user => user.occupation.includes(value)); //best answer

//Alternative answer
const occupationExists = value => users.some(
    user => user.occupation.some(job => job === value)
);

console.log( occupationExists('Teacher') );
console.log( occupationExists('Developer') );

about 4 years ago · Juan Pablo Isaza 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