Last active
June 19, 2019 21:38
-
-
Save KryptikOne/d08e170492f9f785592bcd8d7d1f08de to your computer and use it in GitHub Desktop.
Check if Array Contains Item - http://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * A function to determine if an array contains an item | |
| * @param needle - [Number||String] - The array to search through | |
| * @returns [boolean] - Returns true or false | |
| */ | |
| function arrContainsItem(needle) { | |
| var findNaN = needle !== needle; // Per spec, the way to identify NaN is that it is not equal to itself | |
| var indexOf; | |
| if(!findNaN && typeof Array.prototype.indexOf === 'function') { | |
| indexOf = Array.prototype.indexOf; | |
| } else { | |
| indexOf = function(needle) { | |
| var i = -1, index = -1; | |
| for(i = 0; i < this.length; i++) { | |
| var item = this[i]; | |
| if((findNaN && item !== item) || item === needle) { | |
| index = i; | |
| break; | |
| } | |
| } | |
| return index; | |
| }; | |
| } | |
| return indexOf.call(this, needle) > -1; | |
| } | |
| // Usage | |
| var arrayToCheck = ["string", 24]; | |
| console.log(arrContainsItem.call(arrayToCheck, itemToCheckFor)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment