Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

265
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!