find-if-an-item-is-in-a-javascript-array

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]


up vote589down votefavorite

153

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:

function include(arr, obj) {
    for(var i=0; i<arr.length; i++) {
        if (arr[i] == obj) return true;
    }
}

include([1,2,3,4], 3); // true
include([1,2,3,4], 6); // undefined

javascript arrays


shareimprove this question

edited Jan 6 at 21:05

Gothdo

18.4k104879

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.

 

    

See: stackoverflow.com/a/25765186/1320932 – dr.dimitru Sep 10 ‘14 at 12:18
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 

add a comment

8 Answers

activeoldestvotes


up vote565down voteaccepted

function include(arr,obj) {
    return (arr.indexOf(obj) != -1);
}

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:

      if (!Array.prototype.indexOf)
      {
    
           Array.prototype.indexOf = function(searchElement /*, fromIndex */)
    
        {
    
        "use strict";
    
        if (this === void 0 || 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 > 0)
        {
          n = Number(arguments[1]);
          if (n !== n)
            n = 0;
          else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
            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;
      };
    
    }
  2. Daniel James‘s version:
    if (!Array.prototype.indexOf) {
      Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
      };
    }
  3. roosteronacid‘s version:
    Array.prototype.hasObject = (
      !Array.indexOf ? function (o)
      {
        var l = this.length + 1;
        while (l -= 1)
        {
            if (this[l - 1] === o)
            {
                return true;
            }
        }
        return false;
      } : function (o)
      {
        return (this.indexOf(o) !== -1);
      }
    );

shareimprove this answer

edited Nov 29 ‘12 at 10:40

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

add a comment


up vote188down vote

If you are using jQuery:

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

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


shareimprove this answer

edited Apr 23 ‘16 at 4:28

ozgur

18.1k82965

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

add a comment


up vote31down vote

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:

if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (obj, fromIndex) {
        if (fromIndex == null) {
            fromIndex = 0;
        } else if (fromIndex < 0) {
            fromIndex = Math.max(0, this.length + fromIndex);
        }
        for (var i = fromIndex, j = this.length; i < j; i++) {
            if (this[i] === obj)
                return i;
        }
        return -1;
    };
}

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:

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

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.


shareimprove this answer

edited Jul 26 ‘12 at 15:21

Bill the Lizard

233k140455746

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  

blogs.sun.com/greimer/resource/loop-test.html – roosteronacid Sep 28 ‘08 at 11:37
    

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

add a comment


up vote9down vote

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.


shareimprove this answer

edited Sep 27 ‘08 at 16:00

answered Sep 27 ‘08 at 15:50

assortedslog

1013

 

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

add a comment


up vote9down vote

assuming .indexOf() is implemented

Object.defineProperty( Array.prototype,‘has‘,
         {
            value:function(o,flag){
                     if(flag === undefined){
                         return this.indexOf(o) !== -1;
                     }
                     else{   // only for raw js object
                         for(var v in this){
                         if(JSON.stringify(this[v]) === JSON.stringify(o)) return true;
                     }
                      return false;
                  },
            // writable:false,
            // enumerable:false
         }
   )

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

//use like
[22 ,‘a‘, {prop:‘x‘}].has(12) // false
["a","b"].has("a") //  true

[1,{a:1}].has({a:1},1) // true
[1,{a:1}].has({a:1}) // false

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


shareimprove this answer

edited Apr 16 ‘16 at 15:34

answered Feb 24 ‘12 at 18:11

bortunac

1,4811212

 
add a comment

up vote3down vote

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:

if (yourArray.indexOf !== undefined) result = yourArray.indexOf(target);
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...


shareimprove this answer

edited Aug 11 ‘11 at 23:55

Peter Mortensen

10.8k1375109

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

add a comment


up vote3down vote

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.

var utils = {};

/**
 * utils.isArray
 *
 * Best guess if object is an array.
 */
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     }
     // then check for obvious falses
     if (typeof obj !== ‘object‘) {
         return false;
     }
     if (utils.type(obj) === ‘array‘) {
         return true;
     }
     return false;
 };

/**
 * utils.type
 *
 * Attempt to ascertain actual object type.
 */
utils.type = function(obj) {
    if (obj === null || typeof obj === ‘undefined‘) {
        return String (obj);
    }
    return Object.prototype.toString.call(obj)
        .replace(/\[object ([a-zA-Z]+)\]/, ‘$1‘).toLowerCase();
};

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

/**
 * Adding hasOwnProperty method if needed.
 */
if (typeof Object.prototype.hasOwnProperty !== ‘function‘) {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];
    };
}

And finally this in_array function:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
            }
        }
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;
            }
        }
    }

    return false;
}

shareimprove this answer

edited Aug 22 ‘11 at 7:47

answered Aug 17 ‘11 at 12:57

Ariana Carter-Weir

1,094616

 

    

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

add a comment


up vote3down vote

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


shareimprove this answer

edited Nov 2 ‘12 at 2:16

Dan Dascalescu

38k15144184

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
    

@VinkoVrsalovic: the URL has changed to developer.mozilla.org/en-US/docs/JavaScript/Reference/… – Dan Dascalescu Nov 2 ‘12 at 2:14

add a comment

时间: 2024-10-05 00:53:24

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

javascript Array.push pop unshit shit

HTML代码: 1 <!DOCTYPE html> 2 <html lang="en"> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Document</title> 7 <style type="text/css"> 8 *{font-family:Consolas;font-style: italic} 9 .sh

JavaScript Array --&gt;map()、filter()、reduce()、forEach()函数的使用

题目: 1.得到 3000 到 3500 之内工资的人. 2.增加一个年龄的字段,并且计算其年龄. 3.打印出每个人的所在城市 4.计算所有人的工资的总和. 测试数据: function getData() { var arr = [{ id: 1, name: 'ohzri', birth: '1999.09.09', city: '湖北', salary: 9379 }, { id: 2, name: 'rqgfd', birth: '1999.10.28', city: '湖北', sal

javascript Array学习

首先感谢Dash 我再也不用到处乱找文档了 再次感谢日食记 让我的看到了世界的美好 好的 我们进入正题 注解 我所有的学习心得都建立在ECMAscript5之后 IE9之前的浏览器概不负责 javascript Array是一个好玩的对象 如何检测她呢 首先instanceof是个不错的方法 if (value instanceof Array) { } 不过根据javascript高级程序设计说 这样做 如果一个人重新构造了Array函数 你完了 so 这样 if(Arrays.isArray

JavaScript - Array对象的使用 及 数组排序 sort

<html> <head> <head> <body> <script language="javascript"> // Array对象 // 第一种构造方法 var arr = new Array(); alert(arr.length); arr[0] = 520 ; arr[1] = "wjp" ; alert(arr.length); // 第二种构造方法 // Array(4) ; // 第三种

Javascript Array

Arrays Arrays are zero-indexed, ordered lists of values. They are a handy way to store a set of related items of the same type (such as strings), though in reality, an array can include multiple types of items, including other arrays. To create an ar

JavaScript Array对象介绍

Array 数组 1. 介绍 数组是值的有序集合.每个值叫做一个元素,而每个元素在数组中有一个位置,以数字表示,称为索引.JavaScript数组是无类型:数组元素可以是任意类型,并且同一个数组中的不同元素也可能有不同的类型. --<JavaScript权威指南(第六版)> 2. 定义 var names = new Array("张三", "李四", "王五"); //或者 var names = ["张三",

JavaScript Array(数组)对象

一,定义数组 数组对象用来在单独的变量名中存储一系列的值. 创建 Array 对象的语法: new Array(); new Array(size); new Array(element0, element1, ..., elementn); 参数 参数 size 是期望的数组元素个数.返回的数组,length 字段将被设为 size 的值. 参数 element ..., elementn 是参数列表.当使用这些参数来调用构造函数 Array() 时,新创建的数组的元素就会被初始化为这些值.它

JavaScript Array 对象参考手册

JavaScript Array 对象 Array 对象 Array 对象用于在变量中存储多个值: var cars = ["Saab", "Volvo", "BMW"]; 第一个数组元素的索引值为 0,第二个索引值为 1,以此类推. 更多有关JavaScript Array参考手册请参考 JavaScript Array 对象手册. Array 对象属性 方法 描述 concat() 连接两个或更多的数组,并返回结果. every() 检测数值

Javascript Array Distinct

javascript 没有原生的Distinct功能 . (至少现在还没有)但我们可以通过简单的script 自己实现 . Distinct就是把数组中重复出现2次或以上的值给删除掉,确保数组内每个值都是唯一的 . 我相信大家开始的时候都会和我用同一个方法来处理.那就是开一个新的数组(空),然后 for loop 旧的数组 ,然后复制进去新的数组里面,每次复制进去的时候先检查一篇新数组内是否有了这个值,有了就跳过,没有才加进去 . 代码 :  var old_array = [1, 2, 3,

Javascript Array 非常用方法解析

1. map var ary = Array(3); ary[0] = 2 ary.map(function(elem) { return '1'; }); 结果是["1", undefined * 2], 因为map 只能被初始化过的数组成员调用 2. reduce [].reduce(Math.pow): //typeError, 空数组上调用reduce [3,2,1].reduce(function(x, y) { console.log(x, y); return Math.