When one thinks of searching an array using JavaScript, you are tempted to use the indexOf method, which is as simple as using arr.indexOf(item). However remember that the indexOf or lastIndexOf methods have been formalized in ECMAScript 5. So they are not supported by all browsers (like IE8 does not support, although IE9 Preview supports it).
Now you have a couple of options using which you can use JavaScript to search an array, cross-browser.
Using JavaScript (implementation of indexOf by Mozilla)
Mozilla has provided a cross-browser implementation of the indexOf method which is as follows
<script type="text/javascript">
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function (searchElement /*, fromIndex */) {
"use strict";
if (this === void 0 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 > 0) {
n = Number(arguments[1]);
if (n !== n)
n = 0;
else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
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;
};
}
// Now you can use
var nums = new Array("one", "two", "three", "four");
alert(nums.indexOf("two"));
</script>
The code above returns the first index at which a given element (in our case “two”) can be found in the array, or -1 if it is not present. Since “two” is present in the array, the alert box displays the value 1.
Using jQuery
The jQuery inArray searches for a specified value within an array and return its index (or -1 if not found)
The search can be done using just one line of jQuery code as shown below
<head>
<title>Search if Item exists in Array by DevCurry.com</title>
<script type="text/javascript" src="
http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js">
</script>
<script type="text/javascript">
var nums = new Array("one", "two", "three", "four");
alert($.inArray("two", nums));
</script>
</head>
The jQuery code behind $.inArray() seems much more efficient than the Mozilla prototype extension. Do you know which one has better performance against large arrays?
ReplyDelete//jQuery Source for $.inArray()
if ( array.indexOf ) {
return array.indexOf( elem );
}
for ( var i = 0, length = array.length; i < length; i++ ) {
if ( array[ i ] === elem ) {
return i;
}
}
return -1;
Matthew: My vote goes for the $.in Array()!
ReplyDelete