Reputation: 6030
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
Upvotes: 5
Views: 58675
Reputation: 659
Just use includes
.
var array1 = [1, 2, 3];
console.log(array1.includes(2)); // true
Upvotes: 13
Reputation: 150020
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.
Upvotes: 2
Reputation: 3136
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.
Upvotes: 8
Reputation: 5533
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;
}
Upvotes: 1
Reputation: 76880
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;
};
}
Upvotes: 0