JokerMartini
JokerMartini

Reputation: 6147

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

Upvotes: 1

Views: 76

Answers (3)

SteveGreenley
SteveGreenley

Reputation: 688

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

Upvotes: 0

Parvesh Kumar
Parvesh Kumar

Reputation: 1144

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

Upvotes: 2

user18137037
user18137037

Reputation: 36

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

Upvotes: 2

Related Questions