简体   繁体   中英

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]
}
const needle = 5;
Object.values(sets).findIndex(a => a.find(b => b === needle))

returns position number or -1

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM