JavaScript in_array
Checks if the given value exists in the array
1 2 3 4 56 7 8 9 1011 12 13 14 1516 17 18 19 2021 22 23 24 2526 27 28 29 3031 32 33 34 3536 37 | function in_array (needle, haystack, argStrict) { // Checks if the given value exists in the array // // version: 1008.1718 // discuss at: http://phpjs.org/functions/in_array // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: vlado houba // + input by: Billy // + bugfixed by: Brett Zamir (http://brett-zamir.me) // * example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']); // * returns 1: true // * example 2: in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'}); // * returns 2: false // * example 3: in_array(1, ['1', '2', '3']); // * returns 3: true // * example 3: in_array(1, ['1', '2', '3'], false); // * returns 3: true // * example 4: in_array(1, ['1', '2', '3'], true); // * returns 4: false var key = '', strict = !!argStrict; if (strict) { for (key in haystack) { if (haystack[key] === needle) { return true; } } } else { for (key in haystack) { if (haystack[key] == needle) { return true; } } } return false; } |
Examples
» Example 1
Running
1 | in_array('van', ['Kevin', 'van', 'Zonneveld']); |
Should return
1 | true |
» Example 2
Running
1 | in_array('vlado', {0: 'Kevin', vlado: 'van', 1: 'Zonneveld'}); |
Should return
1 | false |
Dependencies
No dependencies, you can use this function standalone.
Open syntax issues
php.js uses JsLint to help us keep our code consistent and prevent some common bugs.
Eventually we want all code to pass or at least take into consideration most fixes suggested by JsLint, following this JsLint configuration we’ve decided on.
Authors
Thanks to the following developers, you get to have in_array goodness in JavaScript.
Of course that had to be:
function in_array (needle, haystack, argStrict)
{
var key = '', strict = !!argStrict;
if (strict)
for (key in haystack)
if ( (strict && haystack[key] === needle) || ( !strict && strict && haystack[key] == needle ) )
return true;
return false;
}
Shorter:
function in_array (needle, haystack, argStrict)
{
var key = '', strict = !!argStrict;
if (strict)
for (key in haystack)
if ( (strict && haystack[key] === needle) ) || ( !strict && strict && haystack[key] == needle )
return true;
return false;
}
@billy: Thanks, fixed now in git: http://github.com/kvz/phpjs/commit/e37089b71ed1d32d1b4b4567c70a684c9d0e16f5
Sorry Drydenmaker and Kevin, it was a noble attempt, but search should be checked against -1, and even if that were corrected, there would still be problems as your version would make in_array('needle', ['needles']) return true.
I believe the solution to the bug Billy found is that the native JavaScript String.prototype.search returns -1 if the needle is not found, not false like in PHP, what this function expects.
Also, turning an array into a string and searching for the needle, while faster, will be incorrect in many situations, such as searching for 'he' against ['the'] will return true, even though 'he' is not in the array.
Is it just me or does in_array("whatever", ["notit"]) return true...
This function is majorly broken. Strings arguments always return true, even if the array is empty!
@ Drydenmaker: Good point. Didn't bench it but obviously an internal function would be faster than anything we can hack.
However your implementation relies on this.is_string which is not a php.js feature.
I replaced it with (typeof(needle)=='string') but it seems that also the second test case (where we don't want to find 'vlado') fails.
So it needs a little bit of work still.
what if you flattened the non-strict side to a string and used a string search to avoid the loop. Something like:
in_array: function (needle, haystack, argStrict) {
var key = '', strict = !!argStrict;
if (strict) {
for (key in haystack) {
if (haystack[key] === needle) {
return true;
}
}
} else {
if (this.is_string(needle)) {
str = haystack.toString();
return (str.search(needle) !== false)
}
for (key in haystack) {
if (haystack[key] == needle) {
return true;
}
}
}
return false;
}
@ vlado houba: Yes using hash tables is really fast. Obviously we don't control our user's data. But we can make an effort to make in_array as fast as reasonably possible, and I see your optimization is not to check for strict every iteration, but check for it once, and use duplicated loops to do further processing.
Though I'm a big fan of DRY, this really makes sense to me and justifies exception so I will implement your proposal. Thanks for sharing!
sorry for posting that same content by mistake...
maybee it seems to be an unimporatnt change but i was working on a text analyzing script where things like this one matters a lot
for fast searching in small arrays i recommend using the value (string or number) as an index (for sure just for short values..), it much cuts the access times and can be used for advanced structures
function in_array(needle, haystack, argStrict)
{
var found = new Boolean(false);
var key;
var strict = new Boolean(argStrict);
if(strict)
{
for (key in haystack)
{
if (haystack[key] === needle)
{
found = true;
break;
}
}
}
else
{
for (key in haystack)
{
if (haystack[key] == needle)
{
found = true;
break;
}
}
}
return found;
}
@Vladimir, it looks like you posted the same code as we currently have... One very small optimization I do see is "return true" and "return false" instead of found=true, etc. If your optimization was using indexOf, be aware that PHP.JS considers objects to be arrays, so we need to handle them as well...
function's preformance can be improoved by following
01.function in_array(needle, haystack, argStrict) {
02. // Checks if the given value exists in the array
03. //
04. // version: 903.1614
05. // discuss at: http://phpjs.org/functions/in_array
06. // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
07. // * example 1: in_array('van', ['Kevin', 'van', 'Zonneveld']);
08. // * returns 1: true
09. var found = false, key, strict = !!argStrict;
10.
11. for (key in haystack) {
12. if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) {
13. found = true;
14. break;
15. }
16. }
return found;
}
@ Java Dude: No but it has been tested (successfully) in Rhino and I believe Google based their js engine on that.
Do you have more information (maybe a line number or something) for us to go on? Thanks in advance!
Has this function been tested on Google Chrome?
I am receiving a: Uncaught TypError when using it but on in Google Chrome.
@ peter: Thank you but according to the PHP manual in_array should return a boolean value. Also, your version doesn't support the optional strict argument, so in it's current form I'm not convinced I should replace our version with yours.
[CODE="Javascript"]
function in_array(value, arr)
{
var key;
for (key in arr)
{
if (arr[key] === value)
{return value; }
}
return null; //false
}
[/CODE]


Brett Zamir
27 Nov '09
Btw, if you are using your version, you should drop the first "if" since it prevents dealing with non-strict cases.
Thanks again!