-6

I'm trying to write a function returnIndex that returns the index of an object in an array, e.g. myArr = [{ "name": "Bob", "age": 4 }, { "name": "Kirk", "age": 11 }], by passing in a given key/value pair: e.g. returnIndex(myArr, "name", "Bob") should return 0.

I tried this:

const myArr = [{ "name": "Bob", "age": 4 }, { "name": "Kirk", "age": 11 }]
const returnIndex = (arr, key, value) => {
    arr.forEach((item, index) => {
        if (item[key] === value) { return index }
    })
}

const i = returnIndex(myArr, "name", "Bob")
console.log(i)

I get undefined i in the console.

But when I create a throw-away variable i:

const myArr = [{ "name": "Bob", "age": 4 }, { "name": "Kirk", "age": 11 }]
const returnIndex = (arr, key, value) => {
    let i
    arr.forEach((item, index) => {
        if (item[key] === value) { i = index }
    })
    return i
}

const i = returnIndex(myArr, "name", "Bob")
console.log(i)

Then it works. Why is it that I cannot return index directly but have to set up a throw-away variable i? I don't understand this -- Help please!

Also if you have a better way to solve this problem, please do share. Cheers!

1 Answers1

1

You could take Array#findIndex, which returns on the first find with the index.

const
    returnIndex = (arr, key, value) => arr.findIndex(item => item[key] === value),
    myArr = [{ "name": "Bob", "age": 4 }, { "name": "Kirk", "age": 11 }],
    i = returnIndex(myArr, "name", "Bob")

console.log(i);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392