5

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

haynar
  • 5,961
  • 7
  • 33
  • 53
  • 1
    Possible duplicate: http://stackoverflow.com/questions/237104/array-containsobj-in-javascript – robert Nov 23 '11 at 10:12

5 Answers5

13

Just use includes.

var array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
4b0
  • 21,981
  • 30
  • 95
  • 142
SyraKozZ
  • 607
  • 8
  • 17
8

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.

David Hu
  • 3,076
  • 24
  • 26
  • thanks for your solution, but the other solution fits to my needs more, so I'm checking that one as the answer – haynar Nov 23 '11 at 10:44
  • Sounds good. JS objects are just hash maps, which @nnnnnn explicitly showed you how to use. :) – David Hu Nov 23 '11 at 11:10
2

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.

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
1

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;
 } 
Selvakumar Ponnusamy
  • 5,363
  • 7
  • 40
  • 78
0

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;
  };
}
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192