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

120
Views
Javascript get Index of Key which contains value

I was wondering if there is a better way to get the Index of Key whose values contain the given value, otherwise it returns Null. In the example below it does what i need, but wasn't sure not sure if there was a simpler way of writing it. I know javascript's syntax is quite powerful and I'm not as familiar with it as others may be.

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

function getValueSetIndex(val) {
let count = 0
  for (const [key, values] of Object.entries(sets)) {
    if (values.includes(val)) {
        return count;
    }
    count += 1
  }
  return null
}

console.log(getValueSetIndex(4))
console.log(getValueSetIndex(20))

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}
const needle = 5;
Object.values(sets).findIndex(a => a.find(b => b === needle))

returns position number or -1

about 4 years ago · Juan Pablo Isaza Report

0

const keyIndex = (obj, value) => {
  const index = Object.keys(obj).findIndex(key => obj[key].includes(value));
  return index > -1 ? index : null;
}
console.log(keyIndex(sets, 8));
about 4 years ago · Juan Pablo Isaza Report

0

I can see where you're coming from. It's often useful to consider how you might eliminate for loops even if you end up using them.

How do you like this version?:

const sets = {
  "Set 1": [2, 3],
  "Set 2": [4, 5],
  "Set 3": [6]
}

const newGetValueSetIndex = val => {
  const result = Object.values(sets)
    .findIndex(
      values => values.includes(val)
    )
  return result === -1 
    ? null 
    : result
}

console.log(newGetValueSetIndex(4))
console.log(newGetValueSetIndex(20))
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!