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 an object?

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.

30 comments

@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.

@kg11 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!

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

Use includes javascript in-build function

var optval = [];

optval.push('A');    
optval.push('B');    
optval.push('C');

We can search string A in javascript array as:

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

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

@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.

@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.

@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
                count++;
                // sets item to undefined
                delete copyArray[w];
            }
        }

        if (count > 0) {
            var a = new Object();
            a.value = originalArray[i];
            a.count = count;
            compressed.push(a);
        }
    }

    return compressed;
};

// It should go something like this:

var testArray = new Array("dog", "dog", "cat", "buffalo", "wolf", "cat", "tiger", "cat");
var newArray = countArray(testArray);
console.log(newArray);

@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.

@ngCourse 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

@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 saved.

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, as of today, September 2018, Array.prototype.some() is fully supported: caniuse.com support table

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

As of today, September 2018, Array.prototype.some() is fully supported: caniuse.com 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! 👍🏻

@yami 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: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

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

Current browsers have Array#includes, which does exactly that, is widely supported, and has a polyfill for older browsers.

> ['joe', 'jane', 'mary'].includes('jane');
true 

You can also use Array#indexOf, which is less direct, but doesn't require Polyfills for out of date browsers.

jQuery offers $.inArray, which is functionally equivalent to Array#indexOf.

underscore.js, a JavaScript utility library, offers _.contains(list, value), alias _.include(list, value), both of which use indexOf internally if passed a JavaScript array.

Some other frameworks 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

@Iulian Onofrei 2014-07-01 08:09:15

doesn't 2 in [1, 2, 3] work too?

@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.

@slicedtoad 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: github.com/tc39/Array.prototype.includes Also this for different ways to use Array.prototype.indexOf(): codereview.stackexchange.com/questions/13941/…

@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

@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.

underscorejs

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

@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.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map

@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.

@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 } ];
    count = 0; 
var n = numbers.length;
for (var i =0;i<n;i++)
{
  if(numbers[i].x==numbers[i].y)
  {count+=1;}
}

alert(count);

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

@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) {
            res.push(arr[i]);
        }
    }
    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);
}

Usage:

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 && tester.call(that, this[i], i, this)) return true;
    } return false;
  };
}

Usage:

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

Bonus

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: https://www.npmjs.com/package/sort-keys


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.

@Tefa 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

@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;
  else
    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

@cocco 2015-05-19 20:23:07

A hopefully faster bidirectional indexOf / lastIndexOf alternative

2015

While the new method includes is very nice, the support is basically zero for now.

It's long time that I was thinking of way to replace the slow indexOf/lastIndexOf functions.

A performant way has already been found, looking at the top answers. From those I chose the contains function posted by @Damir Zekic which should be the fastest one. But it also states that the benchmarks are from 2008 and so are outdated.

I also prefer while over for, but for not a specific reason I ended writing the function with a for loop. It could be also done with a while --.

I was curious if the iteration was much slower if I check both sides of the array while doing it. Apparently no, and so this function is around two times faster than the top voted ones. Obviously it's also faster than the native one. This in a real world environment, where you never know if the value you are searching is at the beginning or at the end of the array.

When you know you just pushed an array with a value, using lastIndexOf remains probably the best solution, but if you have to travel through big arrays and the result could be everywhere, this could be a solid solution to make things faster.

Bidirectional indexOf/lastIndexOf

function bidirectionalIndexOf(a, b, c, d, e){
  for(c=a.length,d=c*1; c--; ){
    if(a[c]==b) return c; //or this[c]===b
    if(a[e=d-1-c]==b) return e; //or a[e=d-1-c]===b
  }
  return -1
}

//Usage
bidirectionalIndexOf(array,'value');

Performance test

http://jsperf.com/bidirectionalindexof

As test I created an array with 100k entries.

Three queries: at the beginning, in the middle & at the end of the array.

I hope you also find this interesting and test the performance.

Note: As you can see I slightly modified the contains function to reflect the indexOf & lastIndexOf output (so basically true with the index and false with -1). That shouldn't harm it.

The array prototype variant

Object.defineProperty(Array.prototype,'bidirectionalIndexOf',{value:function(b,c,d,e){
  for(c=this.length,d=c*1; c--; ){
    if(this[c]==b) return c; //or this[c]===b
    if(this[e=d-1-c] == b) return e; //or this[e=d-1-c]===b
  }
  return -1
},writable:false, enumerable:false});

// Usage
array.bidirectionalIndexOf('value');

The function can also be easily modified to return true or false or even the object, string or whatever it is.

And here is the while variant:

function bidirectionalIndexOf(a, b, c, d){
  c=a.length; d=c-1;
  while(c--){
    if(b===a[c]) return c;
    if(b===a[d-c]) return d-c;
  }
  return c
}

// Usage
bidirectionalIndexOf(array,'value');

How is this possible?

I think that the simple calculation to get the reflected index in an array is so simple that it's two times faster than doing an actual loop iteration.

Here is a complex example doing three checks per iteration, but this is only possible with a longer calculation which causes the slowdown of the code.

http://jsperf.com/bidirectionalindexof/2

@Ekim 2011-05-10 19:14:40

Literally:

(using Firefox v3.6, with for-in caveats as previously noted (HOWEVER the use below might endorse for-in for this very purpose! That is, enumerating array elements that ACTUALLY exist via a property index (HOWEVER, in particular, the array length property is NOT enumerated in the for-in property list!).).)

(Drag & drop the following complete URI's for immediate mode browser testing.)

JavaScript:

  function ObjInRA(ra){var has=false; for(i in ra){has=true; break;} return has;}

  function check(ra){
      return ['There is ',ObjInRA(ra)?'an':'NO',' object in [',ra,'].'].join('')
  }
  alert([
            check([{}]), check([]), check([,2,3]),
            check(['']), '\t (a null string)', check([,,,])
        ].join('\n'));

which displays:

There is an object in [[object Object]].
There is NO object in [].
There is an object in [,2,3].
There is an object in [].
     (a null string)
There is NO object in [,,].

Wrinkles: if looking for a "specific" object consider:

JavaScript: alert({}!={}); alert({}!=={});

And thus:

JavaScript:

 obj = {prop:"value"}; 
 ra1 = [obj]; 
 ra2 = [{prop:"value"}];
 alert(ra1[0] == obj); 
 alert(ra2[0] == obj);

Often ra2 is considered to "contain" obj as the literal entity {prop:"value"}.

A very coarse, rudimentary, naive (as in code needs qualification enhancing) solution:

JavaScript:

  obj={prop:"value"};   ra2=[{prop:"value"}];
  alert(
    ra2 . toSource() . indexOf( obj.toSource().match(/^.(.*).$/)[1] ) != -1 ?
      'found' :
      'missing' );

See ref: Searching for objects in JavaScript arrays.

@Carlos A 2012-01-06 13:43:14

Use:

Array.prototype.contains = function(x){
  var retVal = -1;

  // x is a primitive type
  if(["string","number"].indexOf(typeof x)>=0 ){ retVal = this.indexOf(x);}

  // x is a function
  else if(typeof x =="function") for(var ix in this){
    if((this[ix]+"")==(x+"")) retVal = ix;
  }

  //x is an object...
  else {
    var sx=JSON.stringify(x);
    for(var ix in this){
      if(typeof this[ix] =="object" && JSON.stringify(this[ix])==sx) retVal = ix;
    }
  }

  //Return False if -1 else number if numeric otherwise string
  return (retVal === -1)?false : ( isNaN(+retVal) ? retVal : +retVal);
}

I know it's not the best way to go, but since there is no native IComparable way to interact between objects, I guess this is as close as you can get to compare two entities in an array. Also, extending Array object might not be a wise thing to do, but sometimes it's OK (if you are aware of it and the trade-off).

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

b is the value, and a is the array. It returns true or false:

function(a, b) {
    return a.indexOf(b) != -1
}

@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)

@aelgoa 2013-02-06 12:28:17

the same performance as !=-1 jsperf.com/indexof-check

@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

@Michael Cole 2015-10-22 21:28:30

Just a bit of throw-up, right in my mouth. Absolutely unprofessional code.

@Fx32 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.

@ninjagecko 2012-04-22 05:17:01

While array.indexOf(x)!=-1 is the most concise way to do this (and has been supported by non-Internet Explorer browsers for over decade...), it is not O(1), but rather O(N), which is terrible. If your array will not be changing, you can convert your array to a hashtable, then do table[x]!==undefined or ===undefined:

Array.prototype.toTable = function() {
    var t = {};
    this.forEach(function(x){t[x]=true});
    return t;
}

Demo:

var toRemove = [2,4].toTable();
[1,2,3,4,5].filter(function(x){return toRemove[x]===undefined})

(Unfortunately, while you can create an Array.prototype.contains to "freeze" an array and store a hashtable in this._cache in two lines, this would give wrong results if you chose to edit your array later. JavaScript has insufficient hooks to let you keep this state, unlike Python for example.)

@Matías Cánepa 2013-09-13 17:32:04

Use:

function isInArray(array, search)
{
    return array.indexOf(search) >= 0;
}

// Usage
if(isInArray(my_array, "my_value"))
{
    //...
}

@Ry- 2014-02-26 16:38:53

x ? true : false is usually redundant. It is here.

@Matías Cánepa 2014-05-03 15:40:46

@minitech Why do you say it is redundant?

@Ry- 2014-05-03 17:38:37

array.indexOf(search) >= 0 is already a boolean. Just return array.indexOf(search) >= 0.

@Matías Cánepa 2014-07-29 18:25:18

@minitech well thanks! Actually I didn't know that such a construction could be returned. TIL something new.

@B T 2015-01-15 22:20:07

Literally any construct in javascript can be returned

@Mina Gabriel 2013-10-06 12:25:35

Use:

var myArray = ['yellow', 'orange', 'red'] ;

alert(!!~myArray.indexOf('red')); //true

Demo

To know exactly what the tilde ~ do at this point, refer to this question What does a tilde do when it precedes an expression?.

@Shadow Wizard 2013-10-06 12:33:01

This was already posted year and half ago no need to repeat it.

@T.CK 2018-05-15 14:52:54

Actually, it hasn't been posted. Not as an answer, but as a comment to an answer, and even then it's not clear and concise. Thanks for posting it, Mina Gabriel.

@Pradeep Mahdevu 2014-05-29 16:55:25

ECMAScript 6 has an elegant proposal on find.

The find method executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, find immediately returns the value of that element. Otherwise, find returns undefined. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values.

Here is the MDN documentation on that.

The find functionality works like this.

function isPrime(element, index, array) {
    var start = 2;
    while (start <= Math.sqrt(element)) {
        if (element % start++ < 1) return false;
    }
    return (element > 1);
}

console.log( [4, 6, 8, 12].find(isPrime) ); // Undefined, not found
console.log( [4, 5, 8, 12].find(isPrime) ); // 5

You can use this in ECMAScript 5 and below by defining the function.

if (!Array.prototype.find) {
  Object.defineProperty(Array.prototype, 'find', {
    enumerable: false,
    configurable: true,
    writable: true,
    value: function(predicate) {
      if (this == null) {
        throw new TypeError('Array.prototype.find called on null or undefined');
      }
      if (typeof predicate !== 'function') {
        throw new TypeError('predicate must be a function');
      }
      var list = Object(this);
      var length = list.length >>> 0;
      var thisArg = arguments[1];
      var value;

      for (var i = 0; i < length; i++) {
        if (i in list) {
          value = list[i];
          if (predicate.call(thisArg, value, i, list)) {
            return value;
          }
        }
      }
      return undefined;
    }
  });
}

@Madbreaks 2016-08-16 17:38:11

Related Questions

Sponsored Content

3 Answered Questions

61 Answered Questions

[SOLVED] How do I correctly clone a JavaScript object?

78 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5655456 View
  • 7030 Score
  • 78 Answer
  • Tags:   javascript arrays

38 Answered Questions

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

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

73 Answered Questions

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

  • 2008-11-05 00:13:08
  • Kevin
  • 1586580 View
  • 2117 Score
  • 73 Answer
  • Tags:   javascript

54 Answered Questions

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

86 Answered Questions

[SOLVED] How do JavaScript closures work?

43 Answered Questions

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

53 Answered Questions

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

Sponsored Content