If you are familiar with PHP, where you can use the in_array() function to search value in the Array, and it returns the Boolean value ( TRUE or FALSE ) to Check if values are exists in Array.
Contents
There are inbuilt methods in jQuery and JavaScript that return the index position of the value which you can use for the search.
- how you can check whether an Array already contains a specific value or not.
- This requires within the program in some cases like –
- Stop new value from insert if it already exists in an Array.
- Execute script when the Array contains the particular value.
Methods used to Check if values are exists in Array:
- Loop
- indexOf()
- inArray()
1.Loop
- First start with a loop.
- You can easily find the value within an Array by traversing on the Array and check for the value.
Completed Code
Output:
For making your searching process simpler you can use jQuery and JavaScript inbuilt function to Check if values are exists in Array
2.Array.indexOf()
- It is a JavaScript method that returns the index position of the value. If it doesn’t find the value then it returns -1.
- It works both with string and an Array.
Syntax :
Completed Code:
Output:
3.jQuery.inArray()
- It is a jQuery function that returns the index position of the value when it finds the value otherwise -1.
- It also works with string and an Array.
Syntax:
Example:
Output:
4.Conclusion
- Some of the methods which you can use to search your value in the existing Array. Using this you can remove or replace the duplicate values.
- If you are using jQuery within your project then you can simply go with inArray() method otherwise you can indexOf() method.