How do I check if an array includes a value in JavaScript?

Created 25.10.2008 22:14
Viewed 2.85M times
4349 votes

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?

9
Comments
just tested: your way is actually the fastest for across browsers: jsperf.com/find-element-in-obj-vs-array/2 (apart from pre-saving a.length in a variable) while using indexOf (as in $.inArray) is much slower by Jörn Berkefeld, 02.07.2012 11:56
many have replied that the Array#indexOf is your best choice here. But if you want something that can be correctly cast to Boolean, use this: ~[1,2,3].indexOf(4) will return 0 which will evaluate as false, whereas ~[1,2,3].indexOf(3) will return -3 which will evaluate as true. by lordvlad, 02.10.2013 07:59
~ is not what you want to use to convert to a boolean, for that you need !. But in this case you want to check equality with -1, s o the function might endreturn [1,2,3].indexOf(3) === -1; ~ is a binary not, it will invert each bit of the value individually. by mcfedr, 20.06.2014 12:49
IE9 supports indexOf() as per w3schools.com/jsref/jsref_indexof_array.asp. If older browser better approach is to define prototype for indexOf() function as given in Array.indexOf in Internet Explorer by LCJ, 21.01.2015 21:42
@Iordvlad [1,2,3].indexOf(4) will actually return -1. As @mcfedr pointed out, ~ is the bitwise-NOT operator, see ES5 11.4.8. Thing is, since the binary representation of -1 consists of only 1's, it's complement is 0, which evaluates as false. The complement of any other number will be non-zero, hence true. So, ~ works just fine and is often used in conjunction with indexOf. by mknecht, 14.03.2015 05:35
The title is misleading. Where is the [[1,2],[3,4]].includes([3,4]) ? by mplungjan, 02.04.2017 09:20
@brad, when I first read your question, I could not get your idea, an object here is javascript object or a primitive value. Suppose I have an array: const arr = [1, 2, 3, { foo: 1}];. And arr.includes(1) // true but arr.includes({ foo: 1 }) //false by Chau Giang, 05.06.2019 10:36
If items in your array are objects then look at this answer which uses some function. by RBT, 18.06.2019 09:51
let arr = ['apple','banana', 1, 2, 4] if (!arr.includes('banana') ) console.log('No') else console.log('Yes') by Jakaria Ridoy, 29.04.2020 10:01
Show remaining 4 comments
Answers 50
25
4793

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.

console.log(['joe', 'jane', 'mary'].indexOf('jane') >= 0); //true


Many frameworks also offer similar methods:

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

24.09.2009 19:35
Comments
MooTools also has Array.contains that returns a boolean, which sounds like the real question here. by Ryan Florence, 08.06.2010 14:10
prototype also has Array.include that returns a boolean by user102008, 10.09.2010 22:54
If you are using a good browser, you can just use array.indexOf(object) != -1 by Sam Soffes, 06.10.2010 16:17
@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? by zcrar70, 12.07.2011 10:06
Also, dont use indexOf alone as a condition, because the first element will return 0 and will be evaluated as falsy by plus-, 29.02.2012 17:17
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. by Tim, 22.07.2012 09:45
var inArray = function(a,b,c,d){for(c in b)d|=b[c]===a;return!!d } by Om Shankar, 30.12.2012 18:54
did underscore remove include? by jcolebrand, 16.01.2013 04:04
@jcolebrand I updated the answer. include is still there, but is in the docs listed as an alias for contains by codeape, 16.01.2013 09:11
@Tim I guess it returns -1 to negate the chance of 0 being taken as falsey by Relequestual, 19.08.2013 12:46
I think someone mentioned that you can get around 0 being evaluated as false by using the === operator, if only in passing. by Aaron Mason, 10.07.2014 23:15
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. by DanielST, 21.10.2014 20:31
@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 by Witiko, 21.03.2015 15:44
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/… by AlicanC, 06.04.2015 13:09
Why not provide an example in the answer? if($.inArray(value, array)) > -1 { // found value in array } by Avatar, 07.04.2015 15:50
now 2016, and i still can't use .include and .indexOf properly on non primitive type. by Adi Prasetyo, 29.02.2016 18:47
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); by Kay Gee, 12.10.2018 16:23
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? by Stophface, 24.10.2018 06:40
"widely" is misleading, since IE 11 does not support it by Tomasz Smykowski, 21.03.2019 14:20
I just need to remember indexOf for booth Array and String :) to be safe by User, 26.06.2019 15:03
how to check key and value with includes? by Kapil soni, 02.07.2019 04:51
maybe use IndexOf ^^ by Sandro Schaurer, 10.07.2019 09:47
this answer has so many upvotes but the question asks about objects in arrays, which this does not work with. by Emobe, 02.08.2019 21:30
@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. by Robert, 07.01.2020 21:25
Great answer. NOTE: includes (and indexOf) DO NOT convert type. You'll have to do that in the code I suppose console.log(['joe', 'jane', 'mary', 46].includes(Number('46'))); by ow3n, 17.09.2020 15:41
Show remaining 20 comments
15
467

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
25.10.2008 23:10
Comments
"Proven" is a strong word. JS engines constantly improve, and execution time measured 3 years ago is terribly outdated. by orip, 20.11.2011 08:09
@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. by Damir Zekić, 20.11.2011 10:40
@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. by orip, 20.11.2011 12:45
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). by Chris Stephens, 22.11.2011 21:28
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 by ajax333221, 04.04.2012 19:04
+1 for giving the LINK to the proof of iteration times... eye-opening revelations in relation to looping over HTML elements... by kumarharsh, 21.08.2012 21:56
@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... by Damir Zekić, 12.10.2012 13:18
The best way to do this is check if [1, 2, 3].indexOf(1) > -1 by Devin Rhode, 28.10.2012 23:25
Does your contains function works in all old and new browser? by Thomas, 12.11.2014 17:03
what prototype() does in js? does it use to add any extension to any class or object from out side? by Thomas, 14.11.2014 12:53
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. by mkey, 06.02.2017 15:32
This answer needs to be downvoted or deleted as it is the worst solution to this date (at the time it was good enough). by Marco, 05.08.2019 19:50
@DamirZekić i don't think contains is method in JS , includes is the right syntax here by jaideep_johny, 03.09.2019 20:58
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. by Abion47, 15.04.2020 21:25
Show remaining 10 comments
4
225

indexOf maybe, but it's a "JavaScript extension to the ECMA-262 standard; as such it may not be present in other implementations of the standard."

Example:

[1, 2, 3].indexOf(1) => 0
["foo", "bar", "baz"].indexOf("bar") => 1
[1, 2, 3].indexOf(4) => -1

AFAICS Microsoft does not offer some kind of alternative to this, but you can add similar functionality to arrays in Internet Explorer (and other browsers that don't support indexOf) if you want to, as a quick Google search reveals (for example, this one).

25.10.2008 22:49
Comments
actually, there is an example of the an implementation of the indexOf extension for browsers that do not support it on the developer.mozilla.org page you linked to. by Lloyd Cotten, 24.03.2009 21:24
actually, if you add indexof to the prototype of Array for browsers that don't support it (i.e. IE7) they will also try to loop over this function when looping through the items in the array. nasty. by CpILL, 11.07.2012 09:13
IE9 now supports this by Liam, 29.05.2014 14:33
is it applicable to check for the Object .? i don't think it works in case of the Object by Himesh Aadeshara, 25.05.2018 04:19
3
182

ECMAScript 7 introduces Array.prototype.includes.

It can be used like this:

[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false

It also accepts an optional second argument fromIndex:

[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true

Unlike indexOf, which uses Strict Equality Comparison, includes compares using SameValueZero equality algorithm. That means that you can detect if an array includes a NaN:

[1, 2, NaN].includes(NaN); // true

Also unlike indexOf, includes does not skip missing indices:

new Array(5).includes(undefined); // true

Currently it's still a draft but can be polyfilled to make it work on all browsers.

01.01.2015 01:40
Comments
Not supported for IE and Microsfot Edge (2015) (developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…‌​) by Adriano Resende, 05.11.2015 23:04
Also relevant, the ES7 compatibility table (looks like chrome supports it now) by styfle, 11.03.2016 20:25
is it applicable to check for the Object .? i don't think it works in case of the Object by Himesh Aadeshara, 25.05.2018 04:18
5
171

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 an 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: caniuse.com support table

18.07.2014 14:36
Comments
As of today, September 2018, Array.prototype.some() is fully supported: caniuse.com support table by jamess, 14.09.2018 22:03
Working in Node >=8.10 for AWS Node.js Lambda, so this is great. Very clean and simple solution! 👍🏻 by Jordan, 20.09.2018 22:48
@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/… by Kamil Witkowski, 24.01.2019 14:32
Does some short-circuit? Or does it iterate the entire array even if it's found a value? by Douglas Gaskell, 03.10.2019 00:06
@DouglasGaskell it aborts the iteration once found (mentioned in the answer) by Michael, 14.10.2019 12:28
5
118

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
24.03.2012 04:59
Comments
It returns true if "b" is in the array "a"... I don't know how else to explain it... by william malo, 16.06.2012 00:41
This part I dont understand "!!~". And I think this will not work in IE8 because IE8 doesnt support indexOf() on Array object. by svlada, 18.06.2012 05:29
"~" 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) by william malo, 19.06.2012 14:41
Cool, but seriously for the sake of simplicity y not just a.indexOf(b)>-1, since ">-1".length === "!!~".length by User, 16.12.2014 15:35
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. by okdewit, 19.01.2016 11:18
4
83

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;
        };
}
27.10.2008 00:38
Comments
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? by Avi Flax, 11.07.2010 12:31
They aren't equvialent. [].indexOf is a shorthand for Array.prototype.indexOf. Us paranoid-defensive Javascript programmers avoid extending native prototypes at all cost. by Már Örlygsson, 14.07.2010 12:03
Isn't [].indexOf creating a new array and then accessing indexOf, whilst Array.prototype.indexOf just accesses the prototype directly? by alex, 08.03.2011 11:47
@alex yes [].indexOf === Array.prototype.indexOf (try it out in FireBug), but conversely [].indexOf !== Array.indexOf. by Már Örlygsson, 11.03.2011 13:32
5
59

Use:

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

// Usage
if(isInArray(my_array, "my_value"))
{
    //...
}
13.09.2013 17:32
Comments
x ? true : false is usually redundant. It is here. by Ry-, 26.02.2014 16:38
@minitech Why do you say it is redundant? by Matías Cánepa, 03.05.2014 15:40
array.indexOf(search) >= 0 is already a boolean. Just return array.indexOf(search) >= 0. by Ry-, 03.05.2014 17:38
@minitech well thanks! Actually I didn't know that such a construction could be returned. TIL something new. by Matías Cánepa, 29.07.2014 18:25
Literally any construct in javascript can be returned by B T, 15.01.2015 22:20
2
53

Extending the JavaScript Array object is a really bad idea because you introduce new properties (your custom methods) into for-in loops which can break existing scripts. A few years ago the authors of the Prototype library had to re-engineer their library implementation to remove just this kind of thing.

If you don't need to worry about compatibility with other JavaScript running on your page, go for it, otherwise, I'd recommend the more awkward, but safer free-standing function solution.

27.08.2009 16:45
Comments
I disagree. For-in loops should not be used for arrays for precisely this reason. Using for-in loops will break when using one of the popular js libraries by Tomas, 18.02.2011 14:51
Would this be considered monkey patching? lol Some people like that. by cbmeeks, 10.10.2012 20:36
1
34

One-liner:

function contains(arr, x) {
    return arr.filter(function(elem) { return elem == x }).length > 0;
}
07.01.2015 12:49
Comments
array.filter(e=>e==x).length > 0 is equivalent to array.some(e=>e==x) but some is more efficient by Apolo, 22.04.2016 09:22
1
33

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

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

23.12.2009 15:59
Comments
Although this is obviously helpful to many, it would have been better if a code snippet was added. by Pie 'Oh' Pah, 11.12.2018 19:27
0
33

Performance

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)

Results

enter image description here

Details

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

log('A',A);
log('B',B);
log('C',C);
log('D',D);
log('E',E);
log('F',F);
log('G',G);
log('H',H);
log('I',I);
log('J',J);
log('K',K);
log('L',L);
log('M',M);
log('N',N);
log('O',O);
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

07.01.2020 11:51
0
28

I use the following:

Array.prototype.contains = function (v) {
    return this.indexOf(v) > -1;
}

var a = [ 'foo', 'bar' ];

a.contains('foo'); // true
a.contains('fox'); // false
15.06.2014 01:15
2
24
function contains(a, obj) {
    return a.some(function(element){return element == obj;})
}

Array.prototype.some() was added to the ECMA-262 standard in the 5th edition

12.09.2014 16:55
Comments
if using es6 than it cam be shorten as contains = (a, obj) => a.some((element) => element === obj)) by diEcho, 28.05.2018 04:24
Even IE9 has support for Array.prototype.some() as of ECMAScript 5. by Suncat2000, 17.01.2019 17:45
0
19

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

19.05.2015 20:23
0
17
function inArray(elem,array)
{
    var len = array.length;
    for(var i = 0 ; i < len;i++)
    {
        if(array[i] == elem){return i;}
    }
    return -1;
} 

Returns array index if found, or -1 if not found

27.06.2012 12:32
0
16

We use this snippet (works with objects, arrays, strings):

/*
 * @function
 * @name Object.prototype.inArray
 * @description Extend Object prototype within inArray function
 *
 * @param {mix}    needle       - Search-able needle
 * @param {bool}   searchInKey  - Search needle in keys?
 *
 */
Object.defineProperty(Object.prototype, 'inArray',{
    value: function(needle, searchInKey){

        var object = this;

        if( Object.prototype.toString.call(needle) === '[object Object]' || 
            Object.prototype.toString.call(needle) === '[object Array]'){
            needle = JSON.stringify(needle);
        }

        return Object.keys(object).some(function(key){

            var value = object[key];

            if( Object.prototype.toString.call(value) === '[object Object]' || 
                Object.prototype.toString.call(value) === '[object Array]'){
                value = JSON.stringify(value);
            }

            if(searchInKey){
                if(value === needle || key === needle){
                return true;
                }
            }else{
                if(value === needle){
                    return true;
                }
            }
        });
    },
    writable: true,
    configurable: true,
    enumerable: false
});

Usage:

var a = {one: "first", two: "second", foo: {three: "third"}};
a.inArray("first");          //true
a.inArray("foo");            //false
a.inArray("foo", true);      //true - search by keys
a.inArray({three: "third"}); //true

var b = ["one", "two", "three", "four", {foo: 'val'}];
b.inArray("one");         //true
b.inArray('foo');         //false
b.inArray({foo: 'val'})   //true
b.inArray("{foo: 'val'}") //false

var c = "String";
c.inArray("S");        //true
c.inArray("s");        //false
c.inArray("2", true);  //true
c.inArray("20", true); //false
10.09.2014 12:12
0
17

If you are using JavaScript 1.6 or later (Firefox 1.5 or later) you can use Array.indexOf. Otherwise, I think you are going to end up with something similar to your original code.

25.10.2008 22:44
5
16

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.

25.01.2017 00:22
Comments
This particular chunk of code may work in IE6 (haven't tested), but IE didn't support ES5 until IE9. by Mark Reed, 09.04.2017 12:51
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 by itinance, 14.04.2017 08:45
@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. by Igor Barbashin, 17.04.2017 04:57
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. by Heretic Monkey, 10.10.2019 15:10
@HereticMonkey, true. That's why I added the sort-keys note at the bottom by Igor Barbashin, 16.10.2019 17:44
1
16

If you are checking repeatedly for existence of an object in an array you should maybe look into

  1. Keeping the array sorted at all times by doing insertion sort in your array (put new objects in on the right place)
  2. Make updating objects as remove+sorted insert operation and
  3. Use a binary search lookup in your contains(a, obj).
05.02.2011 18:02
Comments
Or if possible, stop using an Array entirely, and instead use an Object as a dictionary, as MattMcKnight and ninjagecko have suggested. by joeytwiddle, 08.07.2013 17:08
0
12

Use lodash's some function.

It's concise, accurate and has great cross platform support.

The accepted answer does not even meet the requirements.

Requirements: Recommend most concise and efficient way to find out if a JavaScript array contains an object.

Accepted Answer:

$.inArray({'b': 2}, [{'a': 1}, {'b': 2}])
> -1

My recommendation:

_.some([{'a': 1}, {'b': 2}], {'b': 2})
> true

Notes:

$.inArray works fine for determining whether a scalar value exists in an array of scalars...

$.inArray(2, [1,2])
> 1

... but the question clearly asks for an efficient way to determine if an object is contained in an array.

In order to handle both scalars and objects, you could do this:

(_.isObject(item)) ? _.some(ary, item) : (_.indexOf(ary, item) > -1)
21.10.2015 10:57
1
10

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;
    }
  });
}
29.05.2014 16:55
Comments
This is now a standard: ecma-international.org/ecma-262/6.0/#sec-array.prototype.fin‌​d by Madbreaks, 16.08.2016 17:38
0
10

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

22.04.2012 05:17
2
10

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'));

16.11.2015 12:26
Comments
I think return proxy.has(obj) is much cleaner than two lines with if-else statement here by Maciej Bukowski, 18.08.2016 23:30
function contains(arr, obj) { return new Set(arr).has(obj); } by Gordon Bean, 11.03.2020 15:48
2
8

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

06.10.2013 12:25
Comments
This was already posted year and half ago no need to repeat it. by Shadow The Vaccinated Wizard, 06.10.2013 12:33
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. by T.CK, 15.05.2018 14:52
0
8

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
console.log(users);

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.

11.10.2019 17:38
0
7

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

15.12.2018 10:27
0
7

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.

07.04.2019 13:42
1
7

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;
}
02.07.2017 11:31
Comments
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. by Heretic Monkey, 10.10.2019 15:12
2
6

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'));

09.01.2016 06:38
Comments
What should you use if not this? by bryc, 20.02.2017 17:36
@bryc maybe the accepted solution, or another solution from here. If you don't care much for performance, than you can use this by sqram, 16.03.2017 19:49
4
-9

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.

04.08.2010 14:05
Comments
Please don't use a for in loop to iterate over an array - for in loops should be used strictly for objects only. by Yi Jiang, 20.01.2011 16:33
why is it so bad by da coconut, 08.06.2020 10:23
please don't override builtins developers.google.com/web/updates/2018/03/smooshgate by nkitku, 28.10.2020 19:05
1
4

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 => savedTrack.id === track.id)) {
        return;
      }
      playlistTracks.push(track);

      this.setState({
        playlistTracks
      })
    };
26.01.2020 17:21
Comments
What does it have to do with the question asked? by stefanowiczp, 06.02.2020 14:30
0
5

Here's how Prototype does it:

/**
 *  Array#indexOf(item[, offset = 0]) -> Number
 *  - item (?): A value that may or may not be in the array.
 *  - offset (Number): The number of initial items to skip before beginning the
 *      search.
 *
 *  Returns the position of the first occurrence of `item` within the array &mdash; or
 *  `-1` if `item` doesn't exist in the array.
**/
function indexOf(item, i) {
  i || (i = 0);
  var length = this.length;
  if (i < 0) i = length + i;
  for (; i < length; i++)
    if (this[i] === item) return i;
  return -1;
}

Also see here for how they hook it up.

27.08.2009 17:10
1
6

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

alert(count);

05.12.2017 11:16
Comments
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; } } by armand, 13.06.2018 13:32
1
5

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
}
10.01.2016 10:06
Comments
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.. by TygerKrash, 05.08.2016 11:15
0
5
  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!

18.08.2017 04:20
0
5

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

24.04.2020 08:26
1
4

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

25.01.2018 04:03
Comments
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. by Konstantin, 30.03.2018 07:43
0
5

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

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
20.02.2019 12:03
0
4

Or this solution:

Array.prototype.includes = function (object) {
  return !!+~this.indexOf(object);
};
19.06.2017 00:41
1
4

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

06.01.2012 13:43
Comments
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. by Heretic Monkey, 10.10.2019 15:13
0
4

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;
 });
26.06.2018 10:03
0
4

use Array.prototype.includes for example:

const fruits = ['coconut', 'banana', 'apple']

const doesFruitsHaveCoconut = fruits.includes('coconut')// true

console.log(doesFruitsHaveCoconut)

maybe read this documentation from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes

08.06.2020 10:21
0
3

As others have mentioned you can use Array.indexOf, but it isn't available in all browsers. Here's the code from https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/indexOf to make it work the same in older browsers.

indexOf is a recent addition to the ECMA-262 standard; as such it may not be present in all browsers. You can work around this by inserting the following code at the beginning of your scripts, allowing use of indexOf in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming Object, TypeError, Number, Math.floor, Math.abs, and Math.max have their original value.

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 1) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    }
}
12.03.2013 05:44
1
3

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.

29.10.2018 16:42
Comments
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. by Heretic Monkey, 10.10.2019 15:12
0
3

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;
}
05.09.2017 04:34
0
3

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)); 
} 
02.08.2017 11:57
0
-4

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.

10.05.2011 19:14
2
3

Similar thing: Finds the first element by a "search lambda":

Array.prototype.find = function(search_lambda) {
  return this[this.map(search_lambda).indexOf(true)];
};

Usage:

[1,3,4,5,8,3,5].find(function(item) { return item % 2 == 0 })
=> 4

Same in coffeescript:

Array.prototype.find = (search_lambda) -> @[@map(search_lambda).indexOf(true)]
23.11.2012 16:44
Comments
This certainly is much more flexible than many of the other approaches. If one is uncomfortable with the prototype one might consider something like var positionIf = function (predicate,sequence) {return sequence.map(predicate).indexOf(true);}; by dat, 05.06.2013 21:28
A more efficient way to implement this method would be to use a loop and stop applying search_lambda once something is found. by Casey Chu, 10.10.2013 04:49
0
1

Simple solution : ES6 Features "includes" method

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

  arr.includes(2) // true

  arr.includes(93) // false
10.10.2018 07:48