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"];
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.
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.
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.
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.
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:
suggestionList.includes('Kiwi');
which will return a boolean directly. (Does not work in internet explorer, but works in IEdge)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With