derek5. 2008-10-25 22:14 采纳率: 100%
浏览 1144
已采纳

如何检查一个数组是否包含 JavaScript 中的对象?

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.

转载于:https://stackoverflow.com/questions/237104/how-do-i-check-if-an-array-includes-an-object-in-javascript

  • 写回答

30条回答 默认 最新

  • csdnceshi62 2008-10-25 22:44
    关注

    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.

    评论
  • elliott.david 2008-10-25 22:49
    关注

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

    评论
  • ℙℕℤℝ 2008-10-25 23:10
    关注

    Update: As @orip mentions in comments, the linked benchmark was done in 2008, so results may not be relevant for modern browsers. However, you probably need this to support non-modern browsers anyway and they probably haven't been updated since. Always test for yourself.

    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
    
    评论
  • 7*4 2008-10-27 00:38
    关注

    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;
          };
    }
    
    评论
  • lrony* 2009-08-27 16:45
    关注

    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.

    评论
  • 关注

    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.

    评论
  • hurriedly% 2009-12-23 15: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

    评论
  • 喵-见缝插针 2011-02-05 18:02
    关注

    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).
    评论
  • 笑故挽风 2012-01-06 13:43
    关注

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

    评论
  • larry*wei 2012-03-24 04:59
    关注

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

    function(a, b) {
        return a.indexOf(b) != -1
    }
    
    评论
  • elliott.david 2012-04-22 05:17
    关注

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

    评论
  • 三生石@ 2012-06-27 12:32
    关注
    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

    评论
  • 胖鸭 2013-03-12 05:44
    关注

    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;
        }
    }
    
    评论
  • 斗士狗 2013-09-13 17:32
    关注

    Use:

    function isInArray(array, search)
    {
        return array.indexOf(search) >= 0;
    }
    
    // Usage
    if(isInArray(my_array, "my_value"))
    {
        //...
    }
    
    评论
  • 10.24 2013-10-06 12:25
    关注

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

    评论
  • 喵-见缝插针 2014-05-29 16:55
    关注

    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;
        }
      });
    }
    
    评论
  • Lotus@ 2014-06-15 01:15
    关注

    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
    
    评论
  • 7*4 2014-07-18 14:36
    关注

    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

    评论
  • from.. 2014-09-10 12:12
    关注

    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
    
    评论
  • 关注
    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

    评论
  • MAO-EYE 2015-01-01 01:40
    关注

    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.

    评论
  • 谁还没个明天 2015-01-07 12:49
    关注

    One-liner:

    function contains(arr, x) {
        return arr.filter(function(elem) { return elem == x }).length > 0;
    }
    
    评论
  • python小菜 2015-05-19 20:23
    关注

    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

    评论
  • derek5. 2015-10-21 10:57
    关注

    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)
    
    评论
  • YaoRaoLov 2015-11-16 12:26
    关注

    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'));
    
    评论
  • ~Onlooker 2016-01-09 06:38
    关注

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

    </div>
    
    评论
  • from.. 2016-01-10 10:06
    关注

    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
    }
    
    评论
  • 笑故挽风 2017-01-25 00:22
    关注

    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.

    评论
  • 旧行李 2017-07-02 11:31
    关注

    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;
    }
    
    评论
查看更多回答(29条)

报告相同问题?

悬赏问题

  • ¥15 MICE包多重插补后数据集汇总导出
  • ¥15 一道算法分析问题(关于3-MSAT)
  • ¥15 C++ FLUENT 化学反应速率 编写困难
  • ¥15 Python嵌套交叉验证
  • ¥15 linuxkit+elasticsearch
  • ¥15 兄得萌6.13do题😭😭大一小东西的work
  • ¥15 投不到原始数据,gdal投影代码
  • ¥20 卷积混响的代码帮写。。
  • ¥88 借助代码处理雷达影像,识别任意区域洪水前后的被淹没区域,并可视化展示。
  • ¥100 提问关于声学两个频率合成后主观听觉问题