Coder Perfect

Check to see if an array has a value. [duplicate]

Problem

I’m trying to figure out if a value exists in an array.

The following function is what I’m using:

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

The function returns false in all cases.

The following are the array values and function call:

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

Asked by Prasad

Solution #1

This is handled by a utility function in jQuery:

$.inArray(value, array)

This function returns the index of a value in an array. If the array does not include a value, it returns -1.

See also How can I check if an array in JavaScript contains an object?

Answered by codeape

Solution #2

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;
};

You can put it to use in the following way:

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

CodePen validation/usage

Answered by eyelidlessness

Solution #3

The indexOf() function is typically used for this. You might say:

return arrValues.indexOf('Sam') > -1

Answered by Gabriel Hurley

Solution #4

Array is a new feature in ES2016. prototype.includes().

["Sam", "Great", "Sample", "High"].includes("Sam"); // true

According to kangax and MDN, the following platforms are supported:

Babel (using babel-polyfill) or core-js can be used to extend support. A polyfill is also available from MDN:

if (![].includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
    'use strict';
    var O = Object(this);
    var len = parseInt(O.length) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1]) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) {k = 0;}
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  };
}

Answered by Dale

Solution #5

Because of all the concerns with cross-browser compatibility and efficiency, it’s usually always safer to use a library like lodash.

Because you can always count on a widely popular library like underscore to have the most efficient method of accomplishing a utility function like this at any given time.

_.includes([1, 2, 3], 3); // returns true

If you’re concerned about the amount of size that incorporating the entire library will add to your application, know that you can integrate features separately:

var includes = require('lodash/collections/includes');

NOTICE: With older versions of lodash, this was _.contains() rather than _.includes().

Answered by ncabral

Post is based on https://stackoverflow.com/questions/1181575/determine-whether-an-array-contains-a-value