http://stackoverflow.com/questions/143847/best-way-to-find-if-an-item-is-in-a-javascript-array

Best way to find if an item is in a JavaScript array? [duplicate]

 

This question already has an answer here:

What is the best way to find if an object is in an array?

This is the best way I know:

  1. function include(arr, obj) {
  2. for(var i=0; i<arr.length; i++) {
  3. if (arr[i] == obj) return true;
  4. }
  5. }
  6. include([1,2,3,4], 3); // true
  7. include([1,2,3,4], 6); // undefined
asked Sep 27 '08 at 15:41
zimbatm

3,60041411

marked as duplicate by Gothdojavascript Jan 6 at 21:04

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

 
    
3  
2 things: 1.) 'include' is a really bad name for a function that does not modify the state of anything. It's especially bad for a function that simply returns a boolean. 2.) You need to add "return(false);" before the end of the function. – Aquarelle May 12 '15 at 0:57 
    
as of ECMAScript 2016, you can use Array.prototype.includes function: myArray.includes(3); // true – mhdJun 15 '16 at 13:25 
1  
In ES6 you can do something like arr.find(lamda function) , example: [1, 2, 3,4,5].find(x => x == 3). if element is found it is returned else undefined is returned – allsyed Jul 29 '16 at 10:26 

8 Answers

up vote565down voteaccepted
  1. function include(arr,obj) {
  2. return (arr.indexOf(obj) != -1);
  3. }

EDIT: This will not work on IE6, 7 or 8 though. The best workaround is to define it yourself if it's not present:

  1. Mozilla's (ECMA-262) version:

    1. if (!Array.prototype.indexOf)
    2. {
    3. Array.prototype.indexOf = function(searchElement /*, fromIndex */)
    4. {
    5. "use strict";
    6. if (this === void 0 || this === null)
    7. throw new TypeError();
    8. var t = Object(this);
    9. var len = t.length >>> 0;
    10. if (len === 0)
    11. return -1;
    12. var n = 0;
    13. if (arguments.length > 0)
    14. {
    15. n = Number(arguments[1]);
    16. if (n !== n)
    17. n = 0;
    18. else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
    19. n = (n > 0 || -1) * Math.floor(Math.abs(n));
    20. }
    21. if (n >= len)
    22. return -1;
    23. var k = n >= 0
    24. ? n
    25. : Math.max(len - Math.abs(n), 0);
    26. for (; k < len; k++)
    27. {
    28. if (k in t && t[k] === searchElement)
    29. return k;
    30. }
    31. return -1;
    32. };
    33. }
  2. Daniel James's version:

    1. if (!Array.prototype.indexOf) {
    2. Array.prototype.indexOf = function (obj, fromIndex) {
    3. if (fromIndex == null) {
    4. fromIndex = 0;
    5. } else if (fromIndex < 0) {
    6. fromIndex = Math.max(0, this.length + fromIndex);
    7. }
    8. for (var i = fromIndex, j = this.length; i < j; i++) {
    9. if (this[i] === obj)
    10. return i;
    11. }
    12. return -1;
    13. };
    14. }
  3. roosteronacid's version:

    1. Array.prototype.hasObject = (
    2. !Array.indexOf ? function (o)
    3. {
    4. var l = this.length + 1;
    5. while (l -= 1)
    6. {
    7. if (this[l - 1] === o)
    8. {
    9. return true;
    10. }
    11. }
    12. return false;
    13. } : function (o)
    14. {
    15. return (this.indexOf(o) !== -1);
    16. }
    17. );
answered Sep 27 '08 at 15:45
Vinko Vrsalovic

172k36279330
 
    
I'm curious as to why your version of the Mozilla function is so different from the website you're linking to. Did you modify it yourself or is it just an old version or something? – Shenjoku Mar 11 '14 at 1:16
4  
@Shenjoku: "answered Sep 27 '08 at 15:45" – Vinko Vrsalovic Mar 11 '14 at 5:49
    
Well, there's my answer haha. I can't tell if there's an older version just by looking at the mozilla website so I wasn't sure. Not that it matters, just a curiosity. In any case this was still helpful so you get an upvote ;) – Shenjoku Mar 13 '14 at 2:24
1  
@mcktimo You actually can delete your own comments - if you mouse over your comment, you will see a small circle with an "X" inside; clicking this will prompt to confirm deletion. – Jesse Apr 18 '14 at 21:06

If you are using jQuery:

  1. $.inArray(5 + 5, [ "8", "9", "10", 10 + "" ]);

For more information: http://api.jquery.com/jQuery.inArray/

answered Mar 27 '10 at 0:37
GerManson

3,80711217
 
    
Note that "inArray" is a misnomer, because it doesn't return boolean value - it returns index of first element found. So if you are checking if element exists you should use if (-1 != $.inArray(...)) .... – johndodo 2 days ago

First, implement indexOf in JavaScript for browsers that don't already have it. For example, see Erik Arvidsson's array extras (also, the associated blog post). And then you can use indexOf without worrying about browser support. Here's a slightly optimised version of his indexOf implementation:

  1. if (!Array.prototype.indexOf) {
  2. Array.prototype.indexOf = function (obj, fromIndex) {
  3. if (fromIndex == null) {
  4. fromIndex = 0;
  5. } else if (fromIndex < 0) {
  6. fromIndex = Math.max(0, this.length + fromIndex);
  7. }
  8. for (var i = fromIndex, j = this.length; i < j; i++) {
  9. if (this[i] === obj)
  10. return i;
  11. }
  12. return -1;
  13. };
  14. }

It's changed to store the length so that it doesn't need to look it up every iteration. But the difference isn't huge. A less general purpose function might be faster:

  1. var include = Array.prototype.indexOf ?
  2. function(arr, obj) { return arr.indexOf(obj) !== -1; } :
  3. function(arr, obj) {
  4. for(var i = -1, j = arr.length; ++i < j;)
  5. if(arr[i] === obj) return true;
  6. return false;
  7. };

I prefer using the standard function and leaving this sort of micro-optimization for when it's really needed. But if you're keen on micro-optimization I adapted the benchmarks that roosterononacid linked to in the comments, to benchmark searching in arrays. They're pretty crude though, a full investigation would test arrays with different types, different lengths and finding objects that occur in different places.

answered Sep 27 '08 at 18:10
Daniel James

3,3591328
 
    
The code examples you are linking to are slow on large arrays. See the comments in my implementation example of a hasItem() function. – roosteronacid Sep 27 '08 at 23:06
    
Take a look at these benchmarks: blogs.sun.com/greimer/resource/loop-test.htm For-loops are slow. But I guess the arrays used in the benchmarks are pretty huge :) – roosteronacid Sep 28 '08 at 11:28
1  
    
I agree. I'm also quite pragmatic. But in the case of optimizing the very basics of the language, I think it's good design to implement functionality as performance-effective as possible. – roosteronacid Sep 28 '08 at 15:14

If the array is unsorted, there isn't really a better way (aside from using the above-mentioned indexOf, which I think amounts to the same thing). If the array is sorted, you can do a binary search, which works like this:

  1. Pick the middle element of the array.
  2. Is the element you're looking for bigger than the element you picked? If so, you've eliminated the bottom half of the array. If it isn't, you've eliminated the top half.
  3. Pick the middle element of the remaining half of the array, and continue as in step 2, eliminating halves of the remaining array. Eventually you'll either find your element or have no array left to look through.

Binary search runs in time proportional to the logarithm of the length of the array, so it can be much faster than looking at each individual element.

answered Sep 27 '08 at 15:50
 
1  
You probably should mention that this approach would be faster on large, sorted arrays than small ones. – roosteronacid Sep 27 '08 at 23:07
9  
why would this be slower on smaller arrays? – vidstige Aug 22 '11 at 7:54
1  
@vidstige: He means it scales well, but isn't necessarily fastest for small inputs. – Lightness Races in OrbitFeb 11 '14 at 12:53 
    
This runs in O(lg n) as opposed to O(n), which is way more scalable – Edmund Sep 22 '14 at 19:09

assuming .indexOf() is implemented

  1. Object.defineProperty( Array.prototype,'has',
  2. {
  3. value:function(o,flag){
  4. if(flag === undefined){
  5. return this.indexOf(o) !== -1;
  6. }
  7. else{ // only for raw js object
  8. for(var v in this){
  9. if(JSON.stringify(this[v]) === JSON.stringify(o)) return true;
  10. }
  11. return false;
  12. },
  13. // writable:false,
  14. // enumerable:false
  15. }
  16. )

!!! do not make Array.prototype.has=function(){... because you'll add an enumerable element in every array and js is broken.

  1. //use like
  2. [22 ,'a', {prop:'x'}].has(12) // false
  3. ["a","b"].has("a") // true
  4. [1,{a:1}].has({a:1},1) // true
  5. [1,{a:1}].has({a:1}) // false

the use of 2nd arg (flag) forces comparation by value instead of reference

answered Feb 24 '12 at 18:11
bortunac

1,4811212
 

It depends on your purpose. If you program for the Web, avoid indexOf, it isn't supported by Internet Explorer 6 (lot of them still used!), or do conditional use:

  1. if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
  2. else result = customSlowerSearch(yourArray, target);

indexOf is probably coded in native code, so it is faster than anything you can do in JavaScript (except binary search/dichotomy if the array is appropriate). Note: it is a question of taste, but I would do a return false; at the end of your routine, to return a true Boolean...

answered Sep 27 '08 at 16:28
PhiLho

30.7k262107
 
    
ha...I shrill to think there's still an IE6 client out there at this point... – beauXjames Aug 15 '14 at 16:25
    
shouldn't there be a "as of 2008" like in wikipedia page so that people know this statement is certainly outdated – allan.simon May 5 '16 at 14:20
2  
@allan.simon Look at my icon (and stats) at the bottom of my answer. Just above, there is "answered Sep 27 '08 at 16:28". It is called a date, and people used to Stack Overflow look at these dates to take answers with a grain of salt... That said, my local public library still has IE6 installed on their computers! (but somebody installed Chrome, fortunately!) – PhiLho May 5 '16 at 22:36

A robust way to check if an object is an array in javascript is detailed here:

Here are two functions from the xa.js framework which I attach to a utils = {} ‘container’. These should help you properly detect arrays.

  1. var utils = {};
  2. /**
  3. * utils.isArray
  4. *
  5. * Best guess if object is an array.
  6. */
  7. utils.isArray = function(obj) {
  8. // do an instanceof check first
  9. if (obj instanceof Array) {
  10. return true;
  11. }
  12. // then check for obvious falses
  13. if (typeof obj !== 'object') {
  14. return false;
  15. }
  16. if (utils.type(obj) === 'array') {
  17. return true;
  18. }
  19. return false;
  20. };
  21. /**
  22. * utils.type
  23. *
  24. * Attempt to ascertain actual object type.
  25. */
  26. utils.type = function(obj) {
  27. if (obj === null || typeof obj === 'undefined') {
  28. return String (obj);
  29. }
  30. return Object.prototype.toString.call(obj)
  31. .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();
  32. };

If you then want to check if an object is in an array, I would also include this code:

  1. /**
  2. * Adding hasOwnProperty method if needed.
  3. */
  4. if (typeof Object.prototype.hasOwnProperty !== 'function') {
  5. Object.prototype.hasOwnProperty = function (prop) {
  6. var type = utils.type(this);
  7. type = type.charAt(0).toUpperCase() + type.substr(1);
  8. return this[prop] !== undefined
  9. && this[prop] !== window[type].prototype[prop];
  10. };
  11. }

And finally this in_array function:

  1. function in_array (needle, haystack, strict) {
  2. var key;
  3. if (strict) {
  4. for (key in haystack) {
  5. if (!haystack.hasOwnProperty[key]) continue;
  6. if (haystack[key] === needle) {
  7. return true;
  8. }
  9. }
  10. } else {
  11. for (key in haystack) {
  12. if (!haystack.hasOwnProperty[key]) continue;
  13. if (haystack[key] == needle) {
  14. return true;
  15. }
  16. }
  17. }
  18. return false;
  19. }
answered Aug 17 '11 at 12:57
 
    
While this may theoretically answer the question, it would be preferable to include the essential parts of the answer here, and provide the link for reference. Also, when you copy/paste the same link-only answer to several very old questions at once, it just looks like spam. – Bill the Lizard Aug 18 '11 at 12:48 
    
Sorry Bill, I really didn't mean it to seem like spam and was just trying to update a few of the old questions about this topic too. I've edited the post here to include the actual answer instead of linking off. – Ariana Carter-Weir Aug 22 '11 at 7:37
    
@Bill, actually re-reading the question, this doesn't even answer it at all. I must have made a mistake. – Ariana Carter-Weir Aug 22 '11 at 7:40

Here's some meta-knowledge for you - if you want to know what you can do with an Array, check the documentation - here's the Array page for Mozilla

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

There you'll see reference to indexOf, added in Javascript 1.6

answered Sep 27 '08 at 15:51
Paul Dixon

194k35253303
 
2  
Weird URL for a manual containing information about Javascript 1.8 and beyond! :) – Vinko Vrsalovic Sep 27 '08 at 15:56
    
this doesnt cover object arrays like the author asked about – 29er May 31 '12 at 6:12
    

find-if-an-item-is-in-a-javascript-array的更多相关文章

  1. javascript array操作

    首先来看一下怎么判断一个对象是不是数组: 1.Array.isArray(obj) 调用数组的isArray方法 2.obj instanceof Array 判断对象是否是Array的实例 3.Ob ...

  2. JavaScript Array -->map()、filter()、reduce()、forEach()函数的使用

    题目: 1.得到 3000 到 3500 之内工资的人. 2.增加一个年龄的字段,并且计算其年龄. 3.打印出每个人的所在城市 4.计算所有人的工资的总和. 测试数据: function getDat ...

  3. JavaScript Array methods performance compare

    JavaScript Array methods performance compare JavaScript数组方法的性能对比 env $ node -v # v12.18.0 push vs un ...

  4. 最全总结 JavaScript Array 方法详解

    JavaScript Array 指南.png Array API 大全 (公众号: 前端自学社区).png 前言 我们在日常开发中,与接口打交道最多了,前端通过访问后端接口,然后将接口数据二次处理渲 ...

  5. JavaScript Array 对象

    JavaScript Array 对象 Array 对象 Array 对象用于在变量中存储多个值: var cars = ["Saab", "Volvo", & ...

  6. JavaScript Array(数组)对象

    一,定义数组 数组对象用来在单独的变量名中存储一系列的值. 创建 Array 对象的语法: new Array(); new Array(size); new Array(element0, elem ...

  7. Javascript Array.prototype.some()

    当我们使用数组时,查找数组中包含某个特殊的项是非常常见的动作.下面例子是一个简单的实现: 01 planets = [ 02     "mercury", 03     " ...

  8. [Javascript ] Array methods in depth - sort

    Sort can automatically arrange items in an array. In this lesson we look at the basics including how ...

  9. Javascript Array 方法整理

    Javascript Array 方法整理 Javascript 数组相关方法 说明 大多数其它编程语言不允许改变数组大小,越界访问索引会报错,但是 javascript不会报错,不过不建议直接修改a ...

  10. JavaScript : Array assignment creates reference not copy

    JavaScript : Array assignment creates reference not copy 29 May 2015 Consider we have an array var a ...

随机推荐

  1. Nginx - rewrite 不区分大小写进行匹配

    Nginx - rewrite 不区分大小写进行匹配 分类: Nginx2014-05-28 19:25 1046人阅读 评论(0) 收藏 举报 Use (?i) to match case-inse ...

  2. [转]James Bach:测试人员的角色

    [转]James Bach:测试人员的角色 2015-05-13 以前,我是个开发人员.我不喜欢这个工作,无尽的压力让我疲惫.我几乎从未感觉到自己的工作做得足够好.我从未有过真正的休息.如果我没做好, ...

  3. C# TextBox常用方法总结

    我们在使用C# TextBox进行开发操作的时候经常会碰到C# TextBox的使用,那么C# TextBox的使用有没有一些常用的技巧呢?如C# TextBox换行的处理,其实就是一些常用的操作,那 ...

  4. 使用ICSharpCode.TextEditor制作一个语法高亮显示的XML编辑器

    使用ICSharpCode.TextEditor制作一个语法高亮显示的XML编辑器 品高工作流 的流程模拟器中使用了一个具有语法高亮和折叠功能的XML编辑器,其核心就是用了SharpDevelop中的 ...

  5. 去除inline-block元素间间距的N种方法<转>

    一.现象描述 真正意义上的inline-block水平呈现的元素间,换行显示或空格分隔的情况下会有间距,很简单的个例子: <input /> <input type="su ...

  6. Android——gridLayout(网格布局)

    <?xml version="1.0" encoding="utf-8"?> <GridLayout xmlns:android=" ...

  7. CSS——div居中,window.open(0

    margin:0 auto 表示什么意思?? margin后面如果只有两个参数的话,第一个表示top和bottom,第二个表示left和right因为0 auto,表示上下边界为0,左右则根据宽度自适 ...

  8. e2fsprogs 移植

    e2fsprogs是用维护ext2,ext3和ext4文件系统的工具程序集.检测和修复文件系统,需要用到其中的fsck, ext2fs等工具, 由于开发板上没有,重新制作文件系统又比较麻烦.所以就需要 ...

  9. 在JAVA中利用public static final的组合方式对常量进行标识

    在JAVA中利用public static final的组合方式对常量进行标识(固定格式). 对于在构造方法中利用final进行赋值的时候,此时在构造之前系统设置的默认值相对于构造方法失效. 常量(这 ...

  10. Java凝视模板

     设置凝视模板的入口: Window->Preference->Java->Code Style->Code Template 然后展开Comments节点就是全部需设置凝 ...