简体   繁体   中英

Checking if array contains given element

I have an array of numbers and dynamically adding new numbers to that array in for loop. But I need to avoid adding values that already exist in array. Is there a JS native way to check the presence of some value in array without doing 2nd nested loop. I don't want to use nested loop because the size of array may vary up to 10000

You can use JavaScript's native Array.prototype.indexOf , supported in most browsers: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf

 var a = [1, 2, 3];
 console.log(a.indexOf(4));   // -1

indexOf is faster than a for-loop but the algorithmic complexity is still O(n^2) . If the size of the array gets much larger, consider a different data structure such as a hash table.

Just use includes .

var array1 = [1, 2, 3];
console.log(array1.includes(2)); // true

You can easily avoid a for loop by using a while loop. [Pause for laughter...] But seriously, even the built-in Array.indexOf() method (supported by most browsers) probably uses a loop internally.

You could use a plain object instead, and add each number to the object as a property, then afterwards take the values from the object and put them in an actual array (or just use them in the object if that is convenient). Then you only have to loop through the "up to 10000" numbers once at the end:

var numbersObj = {},
    numbersArray = [];

// your existing for statement here
for (var i=0; i<something; i++) {
   var currentNumber = somethingElse(); // whatever your existing code is to
                                    // determine the number to add goes here

   // put the number in the object (as a key)
   numersObj[currentNumber] = true;
}

// copy numbers out of object into array
for (var k in numbersObj)
   if (numbersObj.hasOwnProperty(k))
      numbersArray.push(k);

After which numbersArray contains unique numbers only. The if test with .hasOwnProperty() is "optional" depending on your point of view.

Within the first loop you could check if numbersObj already holds the currentNumber :

if (!numbersObj[currentNumber])
   numbersObj[currentNumber] = true;

Or just (over)write it every time like I did in the first code block.

try this,

function eleContainsInArray(arr,element){
    if(arr != null && arr.length >0){
        for(var i=0;i<arr.length;i++){
            if(arr[i] == element)
                return true;
        }
    }
    return false;
 } 

There is Array.indexOf which is supported from some browser, you can use this snippets of code to support all browser

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(elt /*, from*/)
  {
    var len = this.length >>> 0;

    var from = Number(arguments[1]) || 0;
    from = (from < 0)
         ? Math.ceil(from)
         : Math.floor(from);
    if (from < 0)
      from += len;

    for (; from < len; from++)
    {
      if (from in this &&
          this[from] === elt)
        return from;
    }
    return -1;
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM