1

I am trying to ge to see if an array has an exact match to a value. This is what I have so far but it doesn't work. If I search for 'leo' I should get no result but in this case both items in the array both match the value. Does anyone know how to find if there is an exact match in the array? Thanks

var array = ['leon','leonardo'];
array.indexOf('leo') 
2
  • 1
    indexOf() gives -1 for me. jsfiddle.net/WX737 Commented Feb 17, 2012 at 21:49
  • "leo" is not exactly matching any of the values in the array, why do you expect it to be something other than -1? Commented Feb 17, 2012 at 22:03

3 Answers 3

5

The code you have should work just fine. How are you checking the result?

array.indexOf('leo') will return -1 if no match is found.

Sign up to request clarification or add additional context in comments.

Comments

0

I believe in your real code (not your example) you accidentally have a string instead of an array.

Calling indexOf('ab') and indexOf('abcd') on the string 'abcd' will result in both finding a match (returning > -1).

Both would return 0 as they match at the start.

Comments

0

I think You can use array.find() instead of array.indexOf() to solve your problem.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.