Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a list contains a string in javascript? [duplicate]

Tags:

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"]; 
like image 508
Gallaxhar Avatar asked Apr 22 '16 01:04

Gallaxhar


People also ask

How do you check if there are duplicates in a list JavaScript?

To check if an array contains duplicates: Use the Array. some() method to iterate over the array. Check if the index of the first occurrence of the current value is NOT equal to the index of its last occurrence. If the condition is met, then the array contains duplicates.

How do you check if a list contains a string JavaScript?

includes() You can use the includes() method in JavaScript to check if an item exists in an array. You can also use it to check if a substring exists within a string. It returns true if the item is found in the array/string and false if the item doesn't exist.

How do you know if a element is repeated in list?

To check if a list has only unique elements, we can also count the occurrence of the different elements in the list. For this, we will use the count() method. The count() method, when invoked on a list, takes the element as input argument and returns the number of times the element is present in the list.

How do you check if a list contains an item in JavaScript?

JavaScript Array includes() The includes() method returns true if an array contains a specified value. The includes() method returns false if the value is not found. The includes() method is case sensitive.


1 Answers

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/
like image 193
ippi Avatar answered Oct 11 '22 14:10

ippi