Home > Back-end >  Function return true based on name index in an array
Function return true based on name index in an array

Time:07-05

I have a 2d array like this:

  const sample = [
    ['', 'Name 1', ''],
    ['Name 2', '', 'Name 3'],
    ['', 'Name 4', 'Name 5']
  ]

I'm trying to write a function to return true if the index of input name is either 0 or 1 otherwise return false.

I have this:

  function isIndexZeroOrOne(arr, name) {
    for (const row of arr) {
        const i = row.indexOf(name)
        return i === 0 || i === 1 ? true : false      
    }
  }

However, it only seems to work for the first sub array in sample (i.e., sample[0])

It's not working for Name 2: console.log(isIndexZeroOrOne(sample, 'Name 2')) It return false even though it should be true (because the index of Name 2 is 0)

What am I doing wrong?

CodePudding user response:

The return statement ends the loop and exits the function, so you're only checking the first subarray.

You should only return immediately when the condition matches, not when it fails, so you continue testing other array elements.

function isIndexZeroOrOne(arr, name) {
  for (const row of arr) {
    const i = row.indexOf(name)
    if (i === 0 || i === 1) {
      return true;
    }
  }
  return false;
}

Or use the some() method.

function isIndexZeroOrOne(arr, name) {
  return arr.some(el => el[0] === name || el[1] === name);
}

CodePudding user response:

I think it's the way that you've written the ternary. It's evaluating things like this:

return (i === 0) || (i === 1 ? true : false) 

It would be better to do:

if (i=== 1 || i === 0) return true

At the moment, you are only ever checking the first row because you always return true or false.

  • Related