25

How can I test if the string "Orange" without quotes, exists in a list such as the one below, using javascript?

var suggestionList = ["Apple", "Orange", "Kiwi"];
wizzwizz4
  • 6,140
  • 2
  • 26
  • 62
Gallaxhar
  • 976
  • 1
  • 15
  • 28

1 Answers1

37

indexOf() is the default to use in such cases.

if( suggestionList.indexOf("Orange") > -1 ) {
    console.log("success");
}

.indexOf() returns the position in the array (or string) of the found element. When no elements are found it returns -1.

Things to consider:

  • It will return 0 if the first object matches, so you cannot just cast to boolean.
  • Since es2016 you can use suggestionList.includes('Kiwi'); which will return a boolean directly. (Does not work in internet explorer, but works in IEdge)
  • includes polyfill for older browsers: https://babeljs.io/docs/usage/polyfill/
ippi
  • 9,857
  • 2
  • 39
  • 50
  • "indexOf()" seems to be the answer, thank you, but it really seems like an unintuitive name for "find within", do you know why it's called indexOf? – Gallaxhar Apr 22 '16 at 01:10
  • Ah, as I just edited in, it's specific use is to find exactly where (the index) the element is in the array, so on the contrary I find the naming quite fitting. As in: The *index of* `orange` in your array is 1. – ippi Apr 22 '16 at 01:13