HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptCritical

Determine whether an array contains a value

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arraydeterminewhethervaluecontains

Problem

I need to determine if a value exists in an array.

I am using the following function:

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] == obj) {
            return true;
        }
    }
    return false;
}


The above function always returns false.

The array values and the function call is as below:

arrValues = ["Sam","Great", "Sample", "High"]
alert(arrValues.contains("Sam"));

Solution

var contains = function(needle) {
    // Per spec, the way to identify NaN is that it is not equal to itself
    var findNaN = needle !== needle;
    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  -1;
};


You can use it like this:

var myArray = [0,1,2],
    needle = 1,
    index = contains.call(myArray, needle); // true


CodePen validation/usage

Code Snippets

var contains = function(needle) {
    // Per spec, the way to identify NaN is that it is not equal to itself
    var findNaN = needle !== needle;
    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;
};
var myArray = [0,1,2],
    needle = 1,
    index = contains.call(myArray, needle); // true

Context

Stack Overflow Q#1181575, score: 1013

Revisions (0)

No revisions yet.