By brad

2008-10-25 22:14:40 8 Comments

What is the most concise and efficient way to find out if a JavaScript array contains a value?

This is the only way I know to do it:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === obj) {
            return true;
    return false;

Is there a better and more concise way to accomplish this?

This is very closely related to Stack Overflow question Best way to find an item in a JavaScript Array? which addresses finding objects in an array using indexOf.


@Md. Harun Or Rashid 2020-05-24 09:48:16

This may be a detailed and easy solution.

//plain array
var arr = ['a', 'b', 'c'];
var check = arr.includes('a');
console.log(check); //returns true
if (check)
   // value exists in array
   //write some codes

// array with objects
var arr = [
      {x:'a', y:'b'},
      {x:'p', y:'q'}

// if you want to check if x:'p' exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p')
       return elm; // returns length = 1 (object exists in array)

// or y:'q' exists in arr
var check = arr.filter(function (elm){
    if (elm.y == 'q')
       return elm; // returns length = 1 (object exists in array)

// if you want to check, if the entire object {x:'p', y:'q'} exists in arr
var check = arr.filter(function (elm){
    if (elm.x == 'p' && elm.y == 'q')
       return elm; // returns length = 1 (object exists in array)

// in all cases
console.log(check.length); // returns 1

if (check.length > 0)
   // returns true
   // object exists in array
   //write some codes

@Riwaj Chalise 2020-04-24 08:26:33

Use indexOf()

You can use the indexOf() method to check whether a given value or element exists in an array or not. The indexOf() method returns the index of the element inside the array if it is found, and returns -1 if it not found. Let's take a look at the following example:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
var a = "Mango";
checkArray(a, fruits);

function checkArray(a, fruits) {
  // Check if a value exists in the fruits array
  if (fruits.indexOf(a) !== -1) {
    return document.write("true");
  } else {
    return document.write("false");

Use include() Method

ES6 has introduced the includes() method to perform this task very easily. But, this method returns only true or false instead of index number:

var fruits = ["Apple", "Banana", "Mango", "Orange", "Papaya"];
alert(fruits.includes("Banana")); // Outputs: true
alert(fruits.includes("Coconut")); // Outputs: false
alert(fruits.includes("Orange")); // Outputs: true
alert(fruits.includes("Cherry")); // Outputs: false

For further reference checkout here

@Kamil Kiełczewski 2020-01-07 11:51:40


Today 2020.01.07 I perform tests on MacOs HighSierra 10.13.6 on Chrome v78.0.0, Safari v13.0.4 and Firefox v71.0.0 for 15 chosen solutions. Conclusions

  • solutions based on JSON, Set and surprisingly find (K,N,O) are slowest on all browsers
  • the es6 includes (F) is fast only on chrome
  • the solutions based on for (C,D) and indexOf (G,H) are quite-fast on all browsers on small and big arrays so probably they are best choice for efficient solution
  • the solutions where index decrease during loop, (B) is slower probably because the way of CPU cache works.
  • I also run test for big array when searched element was on position 66% of array length, and solutions based on for (C,D,E) gives similar results (~630 ops/sec - but the E on safari and firefox was 10-20% slower than C and D)


enter image description here


I perform 2 tests cases: for array with 10 elements, and array with 1 milion elements. In both cases we put searched element in the array middle.

let log = (name,f) => console.log(`${name}: 3-${f(arr,'s10')}  's7'-${f(arr,'s7')}  6-${f(arr,6)} 's3'-${f(arr,'s3')}`)

let arr = [1,2,3,4,5,'s6','s7','s8','s9','s10'];
//arr = new Array(1000000).fill(123); arr[500000]=7;

function A(a, val) {
    var i = -1;
    var n = a.length;
    while (i++<n) {
       if (a[i] === val) {
           return true;
    return false;

function B(a, val) {
    var i = a.length;
    while (i--) {
       if (a[i] === val) {
           return true;
    return false;

function C(a, val) {
    for (var i = 0; i < a.length; i++) {
        if (a[i] === val) return true;
    return false;

function D(a,val)
    var len = a.length;
    for(var i = 0 ; i < len;i++)
        if(a[i] === val) return true;
    return false;

function E(a, val){  
  var n = a.length-1;
  var t = n/2;
  for (var i = 0; i <= t; i++) {
        if (a[i] === val || a[n-i] === val) return true;
  return false;

function F(a,val) {
	return a.includes(val);

function G(a,val) {
	return a.indexOf(val)>=0;

function H(a,val) {
	return !!~a.indexOf(val);

function I(a, val) {
  return a.findIndex(x=> x==val)>=0;

function J(a,val) {
	return a.some(x=> x===val);

function K(a, val) {
  const s = JSON.stringify(val);
  return a.some(x => JSON.stringify(x) === s);

function L(a,val) {
	return !a.every(x=> x!==val);

function M(a, val) {
  return !!a.find(x=> x==val);

function N(a,val) {
	return a.filter(x=>x===val).length > 0;

function O(a, val) {
  return new Set(a).has(val);

This shippet only presents functions used in performance tests - it not perform tests itself!

Array small - 10 elements

You can perform tests in your machine HERE

enter image description here

Array big - 1.000.000 elements

You can perform tests in your machine HERE

enter image description here

@codeape 2009-09-24 19:35:24

Modern browsers have Array#includes, which does exactly that and is widely supported by everyone except IE:

console.log(['joe', 'jane', 'mary'].includes('jane')); //true

You can also use Array#indexOf, which is less direct, but doesn't require polyfills for outdated browsers.

Many frameworks also offer similar methods:

Notice that some frameworks implement this as a function, while others add the function to the array prototype.

@Ryan Florence 2010-06-08 14:10:21

MooTools also has Array.contains that returns a boolean, which sounds like the real question here.

@user102008 2010-09-10 22:54:30

prototype also has Array.include that returns a boolean

@Sam Soffes 2010-10-06 16:17:24

If you are using a good browser, you can just use array.indexOf(object) != -1

@zcrar70 2011-07-12 10:06:38

@user102008: MDN doesn't include any reference to Array.include (MDN Array Reference - I was looking to see what version of JS that was in.) Where did you see a reference to that method?

@plus- 2012-02-29 17:17:09

Also, dont use indexOf alone as a condition, because the first element will return 0 and will be evaluated as falsy

@Tim 2012-07-22 09:45:56

inArray is a terrible name for a function that returns the index of the element, and -1 if it doesn't exist. I would expect a boolean to be returned.

@Om Shankar 2012-12-30 18:54:24

var inArray = function(a,b,c,d){for(c in b)d|=b[c]===a;return!!d }

@jcolebrand 2013-01-16 04:04:41

did underscore remove include?

@codeape 2013-01-16 09:11:48

@jcolebrand I updated the answer. include is still there, but is in the docs listed as an alias for contains

@Relequestual 2013-08-19 12:46:24

@Tim I guess it returns -1 to negate the chance of 0 being taken as falsey

@Aaron Mason 2014-07-10 23:15:15

I think someone mentioned that you can get around 0 being evaluated as false by using the === operator, if only in passing.

@DanielST 2014-10-21 20:31:59

I thought dart was it's own language. Does it actually compile to JS? Edit: oh, it can be compiled to JS, though it runs best on a browser made to run it.

@Witiko 2015-03-21 15:44:51

@IulianOnofrei: No, 2 in [1,2,3] == true, but 5 in [3,4,5] == false. Why? Because arrays in JavaScripts behave just like regular objects, so 2 in array actually only means that array[2] is defined. Mind that this behaviour is still potentially useful, since JavaScript arrays can be sparse: 2 in [1,2,,3] == false

@AlicanC 2015-04-06 13:09:50

You should also check this proposal: Also this for different ways to use Array.prototype.indexOf():…

@Kai Noack 2015-04-07 15:50:40

Why not provide an example in the answer? if($.inArray(value, array)) > -1 { // found value in array }

@Adi Prasetyo 2016-02-29 18:47:38

now 2016, and i still can't use .include and .indexOf properly on non primitive type.

@Kay Gee 2018-10-12 16:23:26

But none of these would work for Array of complex type? it works for string, numbers and all, what abt var arr = [{"id":"1","name":"Joe"},{"id":"2","name":"Smith"}]; var obj = {"id":"1","name":"Joe"}; arr.includes(obj);

@Stophface 2018-10-24 06:40:11

array.includes(foo) does not support objects. I am not sure why this is the accepted answer, because it was asked How do I check if an array includes an object in JavaScript?

@Tomasz Smykowski 2019-03-21 14:20:33

"widely" is misleading, since IE 11 does not support it

@user985399 2019-06-26 15:03:35

I just need to remember indexOf for booth Array and String :) to be safe

@Kapil soni 2019-07-02 04:51:08

how to check key and value with includes?

@Sandro Schaurer 2019-07-10 09:47:51

maybe use IndexOf ^^

@Emobe 2019-08-02 21:30:29

this answer has so many upvotes but the question asks about objects in arrays, which this does not work with.

@Robert 2020-01-07 21:25:27

@Stophface @Emobe How can this not be a correct answer? The question asked for ways to accomplish the same as the supplied code. And Array#includes does exactly what the code in the question does.

@Mamunur Rashid 2020-01-26 17:21:23

Adding a unique item to a another list

searchResults: [
                    name: 'Hello',
                    artist: 'Selana',
                    album: 'Riga',
                    id: 1,
                    name: 'Hello;s',
                    artist: 'Selana G',
                    album: 'Riga1',
                    id: 2,
                    name: 'Hello2',
                    artist: 'Selana',
                    album: 'Riga11',
                    id: 3,
            playlistTracks: [
                name: 'Hello',
                artist: 'Mamunuus',
                album: 'Riga',
                id: 4,
                name: 'Hello;s',
                artist: 'Mamunuus G',
                album: 'Riga1',
                id: 2,
                name: 'Hello2',
                artist: 'Mamunuus New',
                album: 'Riga11',
                id: 3,
            playlistName: "New PlayListTrack",

    // Adding an unique track in the playList
    addTrack = track => {
      if(playlistTracks.find(savedTrack => === {


@stefanowiczp 2020-02-06 14:30:42

What does it have to do with the question asked?

@rlib 2015-11-16 12:26:09

One can use Set that has the method "has()":

function contains(arr, obj) {
      var proxy = new Set(arr);
      if (proxy.has(obj))
        return true;
        return false;

    var arr = ['Happy', 'New', 'Year'];
    console.log(contains(arr, 'Happy'));

@Maciej Bukowski 2016-08-18 23:30:47

I think return proxy.has(obj) is much cleaner than two lines with if-else statement here

@Gordon Bean 2020-03-11 15:48:45

function contains(arr, obj) { return new Set(arr).has(obj); }

@Sanjay Magar 2018-12-15 10:27:24

    function countArray(originalArray) {
    	var compressed = [];
    	// make a copy of the input array
    	var copyArray = originalArray.slice(0);
    	// first loop goes over every element
    	for (var i = 0; i < originalArray.length; i++) {
    		var count = 0;	
    		// loop over every element in the copy and see if it's the same
    		for (var w = 0; w < copyArray.length; w++) {
    			if (originalArray[i] == copyArray[w]) {
    				// increase amount of times duplicate is found
    				// sets item to undefined
    				delete copyArray[w];
    		if (count > 0) {
    			var a = new Object();
    			a.value = originalArray[i];
    			a.count = count;
    	return compressed;
    // It should go something like this:
    var testArray = new Array("dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat");
    var newArray = countArray(testArray);

@Mitul Panchal 2017-12-05 11:16:14

It has one parameter: an array numbers of objects. Each object in the array has two integer properties denoted by x and y. The function must return a count of all such objects in the array that satisfy numbers.x == numbers.y

var numbers = [ { x: 1, y: 1 },
                { x: 2, y: 3 },
                { x: 3, y: 3 },
                { x: 3, y: 4 },
                { x: 4, y: 5 } ];
var count = 0; 
var n = numbers.length;
for (var i =0;i<n;i++)


@armand 2018-06-13 13:32:18

How would you compare the value of x to the next items x value? This isnt working: for (var i = 0; i < n; i++) { if (numbers[i].x == (numbers[i] + 1).x) { count += 1; } }

@Majedur Rahaman 2020-01-23 08:54:28

Object.keys for getting all property names of the object and filter all values that exact or partial match with specified string.

function filterByValue(array, string) {
                return array.filter(o =>
                    Object.keys(o).some(k => o[k].toLowerCase().includes(string.toLowerCase())));

    const arrayOfObject = [{ name: 'Paul', country: 'Canada', }, { name: 'Lea', country: 'Italy', }, { name: 'John', country: 'Italy' }];

    console.log(filterByValue(arrayOfObject, 'lea')); // [{name: 'Lea', country: 'Italy'}]
    console.log(filterByValue(arrayOfObject, 'ita')); // [{name: 'Lea', country: 'Italy'}, {name: 'John', country: 'Italy'}]

You can also filter by specific key such as.

Object.keys(o).some(k =>;

Now you can just check array count after filtered to check value contains or not.

Hope it's helpful.

@william malo 2012-03-24 04:59:59

Let's say you've defined an array like so:

const array = [1, 2, 3, 4]

Below are three ways of checking whether there is a 3 in there. All of them return either true or false.

Native Array method (since ES2016) (compatibility table)

array.includes(3) // true

As custom Array method (pre ES2016)

// Prefixing the method with '_' to avoid name clashes
Object.defineProperty(Array.prototype, '_includes', { value: function (v) { return this.indexOf(v) !== -1 }})
array._includes(3) // true

Simple function

const includes = (a, v) => a.indexOf(v) !== -1
includes(array, 3) // true

@william malo 2012-06-16 00:41:36

It returns true if "b" is in the array "a"... I don't know how else to explain it...

@svlada 2012-06-18 05:29:51

This part I dont understand "!!~". And I think this will not work in IE8 because IE8 doesnt support indexOf() on Array object.

@william malo 2012-06-19 14:41:37

"~" is an operator that floors, inverts and subtracts 1 from a number. indexOf returns -1 if it fails, so "~" turns -1 into "0". using "!!" turns numbers into boleans (!!0===false)

@super 2014-12-16 15:35:30

Cool, but seriously for the sake of simplicity y not just a.indexOf(b)>-1, since ">-1".length === "!!~".length

@okdewit 2016-01-19 11:18:19

I'd call the lack of knowledge about the effects of boolean operators unprofessional. But I agree about the value of readable code, I would certainly wrap this in a clearly labelled function. And that's exactly what most major JS frameworks do.

@Shiva 2019-10-11 17:38:31

Simple solution for this requirement is using find()

If you're having array of objects like below,

var users = [{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "admin"},
{id: "105", name: "user"}];

Then you can check whether the object with your value is already present or not

let data = users.find(object => object['id'] === '104');

if data is null then no admin, else it will return the existing object like below.

{id: "104", name: "admin"}

Then you can find the index of that object in the array and replace the object using below code.

let indexToUpdate = users.indexOf(data);
let newObject = {id: "104", name: "customer"};
users[indexToUpdate] = newObject;//your new object

you will get value like below

[{id: "101", name: "Choose one..."},
{id: "102", name: "shilpa"},
{id: "103", name: "anita"},
{id: "104", name: "customer"},
{id: "105", name: "user"}];

hope this will help anyone.

@Michael 2014-07-18 14:36:31

The top answers assume primitive types but if you want to find out if an array contains an object with some trait, Array.prototype.some() is a very elegant solution:

const items = [ {a: '1'}, {a: '2'}, {a: '3'} ]

items.some(item => item.a === '3')  // returns true
items.some(item => item.a === '4')  // returns false

The nice thing about it is that the iteration is aborted once the element is found so unnecessary iteration cycles are spared.

Also, it fits nicely in an if statement since it returns a boolean:

if (items.some(item => item.a === '3')) {
  // do something

* As jamess pointed out in the comment, at the time of this answer, September 2018, Array.prototype.some() is fully supported: support table

@jamess 2018-09-14 22:03:31

As of today, September 2018, Array.prototype.some() is fully supported: support table

@Jordan 2018-09-20 22:48:50

Working in Node >=8.10 for AWS Node.js Lambda, so this is great. Very clean and simple solution! 👍🏻

@Kamil Witkowski 2019-01-24 14:32:34

@jamess It may be well supported, but remember that Arrow functions in this example are not so well supported. For more details see here:…

@Douglas Gaskell 2019-10-03 00:06:39

Does some short-circuit? Or does it iterate the entire array even if it's found a value?

@Michael 2019-10-14 12:28:19

@DouglasGaskell it aborts the iteration once found (mentioned in the answer)

@Damir Zekić 2008-10-25 23:10:22

Update from 2019: This answer is from 2008 (11 years old!) and is not relevant for modern JS usage. The promised performance improvement was based on a benchmark done in browsers of that time. It might not be relevant to modern JS execution contexts. If you need an easy solution, look for other answers. If you need the best performance, benchmark for yourself in the relevant execution environments.

As others have said, the iteration through the array is probably the best way, but it has been proven that a decreasing while loop is the fastest way to iterate in JavaScript. So you may want to rewrite your code as follows:

function contains(a, obj) {
    var i = a.length;
    while (i--) {
       if (a[i] === obj) {
           return true;
    return false;

Of course, you may as well extend Array prototype:

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

And now you can simply use the following:

alert([1, 2, 3].contains(2)); // => true
alert([1, 2, 3].contains('2')); // => false

@MatrixFrog 2010-08-12 23:16:50

@orip 2011-11-20 08:09:37

"Proven" is a strong word. JS engines constantly improve, and execution time measured 3 years ago is terribly outdated.

@Damir Zekić 2011-11-20 10:40:01

@orip excellent point. But even so, for the slowest browser out there it's still valid. For the modern browsers the difference is either negligible or irrelevant (since they already support indexOf). I've updated the answer, thanks.

@orip 2011-11-20 12:45:20

@Damir - I agree. Perhaps change the sample to use indexOf if available, just so people copy-pasting this code blindly will get the best performance they can.

@Chris Stephens 2011-11-22 21:28:32

extending the Array like this will cause one more issue. if you use for(x in myArray) it will cycle through the prototype methods too, so you need to check if each x is a property now. I'm looking right now to see if there is a way to remedy this without having to redo all my for(in).

@ajax333221 2012-04-04 19:04:09

you should use i in obj && ... === ... because in case of sparse arrays var arr=[];arr[4]="d"; it will wrongly return true when searching for undefined

@kumarharsh 2012-08-21 21:56:40

+1 for giving the LINK to the proof of iteration times... eye-opening revelations in relation to looping over HTML elements...

@Damir Zekić 2012-10-12 13:18:45

@cbmeeks yeah, care is definitely needed. It was probably a case of doing for (o in array) which shouldn't be done when looping through the array generally...

@Devin G Rhode 2012-10-28 23:25:54

The best way to do this is check if [1, 2, 3].indexOf(1) > -1

@Thomas 2014-11-12 17:03:10

Does your contains function works in all old and new browser?

@Thomas 2014-11-14 12:53:21

what prototype() does in js? does it use to add any extension to any class or object from out side?

@mkey 2017-02-06 15:32:21

In nodejs (v7.4.0) on my windows 7 64 bit machine, looking up for a 1 in an array with 10M zeros; the "while" loop takes about 240+ ms, "for" loop (also counting down) takes about 220 ms and "indexOf" method takes about 20 ms. If I fill up that array with some incrementing numbers (0 to 10M-1) and look for -1, while loop becomes faster about 4 times, for loop becomes faster about 8 times and indexOf takes about 25-50% more time. Color me surprised.

@Marco 2019-08-05 19:50:39

This answer needs to be downvoted or deleted as it is the worst solution to this date (at the time it was good enough).

@jaideep_johny 2019-09-03 20:58:02

@DamirZekić i don't think contains is method in JS , includes is the right syntax here

@Abion47 2020-04-15 21:25:54

The performance claim in this approach is dubious. For one, its reverse direction can give a false positive in benchmarks that bias toward elements at the end of the array. For another, running a benchmark in Perflink shows that this code performs at around 9% the speed of includes (for an element near the middle of an array) whereas an identical benchmark run in jsBench shows it coming close to or even sometimes beating includes. (These tests were performed multiple times on the same browser, browser version, and computer.) This is a weird discrepency.

@Rajeev Ranjan 2019-02-20 12:03:34

Use includes javascript in-build function, but not work in Internet Explorer

var optval = [];


We can search string A in javascript array as:

optval.includes('A') // =====> return true

@Sumer 2019-04-07 13:42:50

Surprised that this question still doesn't have latest syntax added, adding my 2 cents.

Let's say we have array of Objects arrObj and we want to search obj in it.

Array.prototype.indexOf -> (returns index or -1) is generally used for finding index of element in array. This can also be used for searching object but only works if you are passing reference to same object.

let obj = { name: 'Sumer', age: 36 };
let arrObj = [obj, { name: 'Kishor', age: 46 }, { name: 'Rupen', age: 26 }];

console.log(arrObj.indexOf(obj));// 0
console.log(arrObj.indexOf({ name: 'Sumer', age: 36 })); //-1

console.log([1, 3, 5, 2].indexOf(2)); //3

Array.prototype.includes -> (returns true or false)

console.log(arrObj.includes(obj));  //true
console.log(arrObj.includes({ name: 'Sumer', age: 36 })); //false

console.log([1, 3, 5, 2].includes(2)); //true

Array.prototype.find -> (takes callback, returns first value/object that returns true in CB).

console.log(arrObj.find(e => e.age > 40));  //{ name: 'Kishor', age: 46 }
console.log(arrObj.find(e => e.age > 40)); //{ name: 'Kishor', age: 46 }

console.log([1, 3, 5, 2].find(e => e > 2)); //3

Array.prototype.findIndex -> (takes callback, returns index of first value/object that returns true in CB).

console.log(arrObj.findIndex(e => e.age > 40));  //1
console.log(arrObj.findIndex(e => e.age > 40)); //1

console.log([1, 3, 5, 2].findIndex(e => e > 2)); //1

Since find and findIndex takes a callback, we can be fetch any object(even if we don't have the reference) from array by creatively setting the true condition.

@Krishna Ganeriwal 2017-08-18 04:20:33

  1. Either use Array.indexOf(Object).
  2. With ECMA 7 one can use the Array.includes(Object).
  3. With ECMA 6 you can use Array.find(FunctionName) where FunctionName is a user defined function to search for the object in the array.

    Hope this helps!

@Alireza 2017-07-02 11:31:12

OK, you can just optimise your code to get the result!

There are many ways to do this which are cleaner and better, but I just wanted to get your pattern and apply to that using JSON.stringify, just simply do something like this in your case:

function contains(a, obj) {
    for (var i = 0; i < a.length; i++) {
        if (JSON.stringify(a[i]) === JSON.stringify(obj)) {
            return true;
    return false;

@Heretic Monkey 2019-10-10 15:12:28

Late note: this doesn't work with, say, contains([{ a: 1, b: 2 }], { b: 2, a: 1 }) because the stringified objects maintain the order of the properties.

@Dennis Allen 2010-08-04 14:05:17

Just another option

// usage: if ( ['a','b','c','d'].contains('b') ) { ... }
Array.prototype.contains = function(value){
    for (var key in this)
        if (this[key] === value) return true;
    return false;

Be careful because overloading javascript array objects with custom methods can disrupt the behavior of other javascripts, causing unexpected behavior.

@MatrixFrog 2010-08-12 23:18:09

@Yi Jiang 2011-01-20 16:33:00

Please don't use a for in loop to iterate over an array - for in loops should be used strictly for objects only.

@DAMMAK 2019-10-16 15:37:13

mutating built-in Object is not really advisable....

@Már Örlygsson 2008-10-27 00:38:57

Here's a JavaScript 1.6 compatible implementation of Array.indexOf:

if (!Array.indexOf) {
    Array.indexOf = [].indexOf ?
        function(arr, obj, from) {
            return arr.indexOf(obj, from);
        } :
        function(arr, obj, from) { // (for IE6)
            var l = arr.length,
                i = from ? parseInt((1 * from) + (from < 0 ? l : 0), 10) : 0;
            i = i < 0 ? 0 : i;
            for (; i < l; i++) {
                if (i in arr && arr[i] === obj) {
                    return i;
            return -1;

@Avi Flax 2010-07-11 12:31:11

This looks great, but a little confused: * Aren't the tests on lines 1 and 3 equivalent? * Wouldn't it be better to test the prototype, and add the function to Array.prototype if necessary?

@Már Örlygsson 2010-07-14 12:03:18

They aren't equvialent. [].indexOf is a shorthand for Array.prototype.indexOf. Us paranoid-defensive Javascript programmers avoid extending native prototypes at all cost.

@alex 2011-03-08 11:47:00

Isn't [].indexOf creating a new array and then accessing indexOf, whilst Array.prototype.indexOf just accesses the prototype directly?

@Már Örlygsson 2011-03-11 13:32:29

@alex yes [].indexOf === Array.prototype.indexOf (try it out in FireBug), but conversely [].indexOf !== Array.indexOf.

@Nitesh Ranjan 2018-10-29 16:42:27

In Addition to what others said, if you don't have a reference of the object which you want to search in the array, then you can do something like this.

let array = [1, 2, 3, 4, {"key": "value"}];

array.some((element) => JSON.stringify(element) === JSON.stringify({"key": "value"})) // true

array.some((element) => JSON.stringify(element) === JSON.stringify({})) // true

Array.some returns true if any element matches the given condition and returns false if none of the elements matches the given condition.

@Heretic Monkey 2019-10-10 15:12:51

Late note: this doesn't work with, say, contains([{ a: 1, b: 2 }], { b: 2, a: 1 }) because the stringified objects maintain the order of the properties.

@Shashwat Gupta 2018-10-10 07:48:52

Simple solution : ES6 Features "includes" method

let arr = [1, 2, 3, 2, 3, 2, 3, 4];

  arr.includes(2) // true

  arr.includes(93) // false

@Durgpal Singh 2018-06-26 10:03:01

I recommended to use underscore library because its return the value and its supported for all browsers.


 var findValue = _.find(array, function(item) {
    return ==;

@MattMcKnight 2009-12-23 15:59:59

Thinking out of the box for a second, if you are making this call many many times, it is vastly more efficient to use an associative array a Map to do lookups using a hash function.

@Pie 'Oh' Pah 2018-12-11 19:27:31

Although this is obviously helpful to many, it would have been better if a code snippet was added.

@Neil Girardi 2018-01-25 04:03:51

If you're working with ES6 You can use a set:

function arrayHas( array, element ) {
    const s = new Set(array);
    return s.has(element)

This should be more performant than just about any other method

@Konstantin 2018-03-30 07:43:13

How is it more performant? At the very least you have to construct the set, which is O(n) (you have to iterate over the array). Just doing linear search (like indexOf does) is also O(n), but only in the worst case. The average case complexity is more like n/2, since if the array includes the element, you'll likely stop somewhere in the middle. Therefore, this method is, on average, slower than Array#includes and Array#indexOf.

@Jeeva 2017-09-05 04:34:58

I was working on a project that I needed a functionality like python set which removes all duplicates values and returns a new list, so I wrote this function maybe useful to someone

function set(arr) {
    var res = [];
    for (var i = 0; i < arr.length; i++) {
        if (res.indexOf(arr[i]) === -1) {
    return res;

@KRRySS 2017-08-02 11:57:35

Using idnexOf() it is a good solution, but you should hide embedded implementation indexOf() function which returns -1 with ~ operator:

function include(arr,obj) { 
    return !!(~arr.indexOf(obj)); 

@Igor Barbashin 2017-01-25 00:22:34

Solution that works in all modern browsers:

function contains(arr, obj) {
  const stringifiedObj = JSON.stringify(obj); // Cache our object to not call `JSON.stringify` on every iteration
  return arr.some(item => JSON.stringify(item) === stringifiedObj);


contains([{a: 1}, {a: 2}], {a: 1}); // true

IE6+ solution:

function contains(arr, obj) {
  var stringifiedObj = JSON.stringify(obj)
  return arr.some(function (item) {
    return JSON.stringify(item) === stringifiedObj;

// .some polyfill, not needed for IE9+
if (!('some' in Array.prototype)) {
  Array.prototype.some = function (tester, that /*opt*/) {
    for (var i = 0, n = this.length; i < n; i++) {
      if (i in this &&, this[i], i, this)) return true;
    } return false;


contains([{a: 1}, {a: 2}], {a: 1}); // true

Why to use JSON.stringify?

Array.indexOf and Array.includes (as well as most of the answers here) only compare by reference and not by value.

[{a: 1}, {a: 2}].includes({a: 1});
// false, because {a: 1} is a new object


Non-optimized ES6 one-liner:

[{a: 1}, {a: 2}].some(item => JSON.stringify(item) === JSON.stringify({a: 1));
// true

Note: Comparing objects by value will work better if the keys are in the same order, so to be safe you might sort the keys first with a package like this one:

Updated the contains function with a perf optimization. Thanks itinance for pointing it out.

@Mark Reed 2017-04-09 12:51:47

This particular chunk of code may work in IE6 (haven't tested), but IE didn't support ES5 until IE9.

@itinance 2017-04-14 08:45:44

For performance reasons you should avoid stringifying. At least you should avoid to JSON.stringify the "obj" on every loop because it is expensive and will slow down you application. Therefor you should capture it before the for-loop in a temp variable

@Igor Barbashin 2017-04-17 04:57:19

@itinance good point. Updated the includes function with your suggestion. I've ran jsperf with my function. It's about 5x slower than lodash's includes. Though lodash doesn't compare by value and can't find {a: 1} in [{a: 1}]. I don't know if any library does it. But I'm curious if there's any more performant and not insanely complex way of doing it.

@Heretic Monkey 2019-10-10 15:10:21

Late note: this doesn't work with, say, contains([{ a: 1, b: 2 }], { b: 2, a: 1 }) because the stringified objects maintain the order of the properties.

@Igor Barbashin 2019-10-16 17:44:20

@HereticMonkey, true. That's why I added the sort-keys note at the bottom

@Maxime Helen 2017-06-19 00:41:49

Or this solution:

Array.prototype.includes = function (object) {
  return !!+~this.indexOf(object);

@user2724028 2016-01-10 10:06:46

You can also use this trick:

var arrayContains = function(object) {
  return (serverList.filter(function(currentObject) {
    if (currentObject === object) {
      return currentObject
    else {
      return false;
  }).length > 0) ? true : false

@TygerKrash 2016-08-05 11:15:02

this seems convoluted. 'object' is a poor name, 'item' might be better. the filter function logic should just be return currentObject === item; and the ternary operator is uncessary..

@sqram 2016-01-09 06:38:43

By no means the best, but I was just getting creative and adding to the repertoire.

Do not use this

Object.defineProperty(Array.prototype, 'exists', {
  value: function(element, index) {

    var index = index || 0

    return index === this.length ? -1 : this[index] === element ? index : this.exists(element, ++index)

// Outputs 1
console.log(['one', 'two'].exists('two'));

// Outputs -1
console.log(['one', 'two'].exists('three'));

console.log(['one', 'two', 'three', 'four'].exists('four'));

@bryc 2017-02-20 17:36:29

What should you use if not this?

@sqram 2017-03-16 19:49:57

@bryc maybe the accepted solution, or another solution from here. If you don't care much for performance, than you can use this

Related Questions

Sponsored Content

82 Answered Questions

[SOLVED] How can I convert a string to boolean in JavaScript?

  • 2008-11-05 00:13:08
  • Kevin
  • 2010722 View
  • 2552 Score
  • 82 Answer
  • Tags:   javascript

96 Answered Questions

[SOLVED] How can I remove a specific item from an array?

  • 2011-04-23 22:17:18
  • Walker
  • 6703258 View
  • 8291 Score
  • 96 Answer
  • Tags:   javascript arrays

3 Answered Questions

61 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

40 Answered Questions

[SOLVED] For-each over an array in JavaScript

57 Answered Questions

[SOLVED] How do I check if an element is hidden in jQuery?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

42 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

66 Answered Questions

[SOLVED] How do I check whether a checkbox is checked in jQuery?

48 Answered Questions

[SOLVED] How to check if an object is an array?

Sponsored Content