jQuery.inArray( search-value, array-or-string-in-which-to-search);
//code to check if a value exists in an array using jQuery <script type='text/javascript'> var fruits_arr = ['Apple','Mango','Grapes','Orange','Fig','Cherry']; var text = "Watermelon"; // Searching in Array console.log( 'Index : ' + jQuery.inArray('Fig', fruits_arr) ); console.log( 'Index : ' + jQuery.inArray('Peach', fruits_arr )); // Searching in String variable console.log( 'Index : ' + jQuery.inArray( "m", text )); </script>
Index : 4 Index : -1 Index : 5
<script type='text/javascript'> //code to check if a value exists in an array using javascript for loop var fruits_arr = ['Apple','Mango','Grapes','Orange','Fig','Cherry']; function checkValue(value,arr){ var status = 'Not exist'; for(var i=0; i<arr.length; i++){ var name = arr[i]; if(name == value){ status = 'Exist'; break; } } return status; } console.log('status : ' + checkValue('Mango', fruits_arr) ); console.log('status : ' + checkValue('Peach', fruits_arr) ); </script>
status : Exist status : Not exist
However, instead of writing a loop for this case, you can use the inbuilt function of Array.indexOf () for the same case. If the value exists, then the function will return the index value of the element, else it will return -1
put-array-or-string-here.indexOf()
//code to check if a value exists in an array using javascript indexOf var fruits_arr = ['Apple','Mango','Grapes','Orange','Fig','Cherry']; var string = "Orange"; // Find in Array fruits_arr.indexOf('Tomato'); fruits_arr.indexOf('Grapes'); // Find in String string.indexOf('g');
-1 2 4
If you are using modern browsers you may also use the includes() function instead of the indexOf() function
Like indexOf() function, theincludes() function also works well with primitive types.
const symbol = Symbol('symbol'); const array = [ 'hello', 300, 0, undefined, null, symbol ];
//code to check if a value exists in an array using includes function array.includes('hello'); // true array.includes(300); // true array.includes(0); // true array.includes(undefined); // true array.includes(null); // true array.includes(symbol); // true
array.indexOf('hello') !== -1; // true array.indexOf(300) !== -1; // true array.indexOf(0) !== -1; // true array.indexOf(undefined) !== -1; // true array.indexOf(null) !== -1; // true array.indexOf(symbol) !== -1; // true
const array = ['MANGO']; array.includes('mango'); // false array.indexOf('mango') !== -1; // false
const array = ['MANGO']; const sameCaseArray = array.map(value => value.toLowerCase()); // ['mango'] sameCaseArray.includes('mango'); // true sameCaseArray.indexOf('mango') !== -1; // true
const array = [NaN]; // 😄 array.includes(NaN); // true // 😞 array.indexOf(NaN) !== -1; // false
We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ...
We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article ...