0

I am trying to find a certain string within an array.

This is my code so far:

function getUserName(arrayName){
for (counter = 0 ; counter < arrayName.length ; counter++){
    check = arrayName[counter].search("Jon");

    if (check != -1){
          result = arrayName[counter];
    }               
    break;
  }
}   

The problem that I am running into is that if there is a name above Jon in the array (e.g Jon_111) the result would be Jon_111 and not Jon

What do I use to tell it to only find and return if it is exactly Jon.

2 Answers2

1

You can use find() to find an array's element (or just indexOf(), depending on use case). To get an exact result only, use ===

let index = arrayName.indexOf('Jon');
// or
let element = arrayName.find(e => e === 'Jon');
baao
  • 71,625
  • 17
  • 143
  • 203
0

Why don't just === ?

  function getUserName(arrayName){
for (counter = 0 ; counter < arrayName.length ; counter++){
    check = arrayName[counter]==="Jon";

    if (check === true){
          result = arrayName[counter];
    }               
    break;
  }
} 
Felix Cen
  • 733
  • 1
  • 6
  • 24