Home > Back-end >  Check if value exists in nested array
Check if value exists in nested array

Time:03-17

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.

CodePudding user response:

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

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

CodePudding user response:

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

CodePudding user response:

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') );

CodePudding user response:

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

let fullOccupation = []

aoo.map(obj => {
  obj.occupation.map(occ => {
    const check = fullOccupation.includes(occ) 
          console.log(occ)
          if(!check)
          {
            fullOccupation.push(occ)
          }else{
                    alert(occ)

          }
  })
})

  • Related