Checking If Element Exists In Array Without Iterating Through It
Solution 1:
No, without using custom dictionary objects (which you seriously don't want to for this) there's no faster way than doing a 'full scan' of all contained objects.
As a general rule of thumb, don't worry about performance in any language or any situation until the total number of iterations hits 5 digits, most often 6 or 7. Scanning a table of 100 elements should be a few milliseconds at worst. Worrying about performance impact before you have noticed performance impact is one of the worst kinds of premature optimization.
Solution 2:
No, you can't know that without iterating the array.
However, note for...in
loops are a bad way of iterating arrays:
- There is no warranty that it will iterate the array with order
- It will also iterate (enumerable) non-numeric own properties
- It will also iterate (enumerable) properties that come from the prototype, i.e., defined in
Array.prototype
andObject.protoype
.
I would use one of these:
for
loop with a numeric index:for (var i=0; i<tempListArray.length; ++i) { if (tempListArray[i].id == Id) { flagExistsLoop = 1; break; } }
Array.prototype.some
(EcmaScript 5):var flagExistsLoop = tempListArray.some(function(item) { return item.id == Id; });
Note it may be slower than the other ones because it calls a function at each step.
for...of
loop (EcmaScript 6):for (var item of tempListArray) { if (item.id == Id) { flagExistsLoop = 1; break; } }
Solution 3:
Depending on your scenario, you may be able to use Array.indexOf() which will return -1 if the item is not present.
Granted it is probably iterating behind the scenes, but the code is much cleaner. Also note how object comparisons are done in javascript, where two objects are not equal even though their values may be equal. See below:
var tempListArray = [{"id":"12","value":false},{"id":"10","value":false},{"id":"9","value":false},{"id":"8","value":false}];
var check1 = tempListArray[2];
var check2 = {"id":"9","value":false};
doCheck(tempListArray, check1);
doCheck(tempListArray, check2);
functiondoCheck(array, item) {
var index = array.indexOf(item);
if (index === -1)
document.write("not in array<br/>");
elsedocument.write("exists at index " + index + "<br/>");
}
Solution 4:
try to use php.js it may help while you can use same php function names and it has some useful functionalities
Solution 5:
There is no way without iterating through the elements (that would be magic).
But, you could consider using an object instead of an array. The object would use the (presumably unique) id
value as the key, and the value could have the same structure you have now (or without the redundant id
property). This way, you can efficiently determine if the id
already exists.
Post a Comment for "Checking If Element Exists In Array Without Iterating Through It"