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

148
Views
Function return true based on name index in an array

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?

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

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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.

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!