JavaScript array_search
Searches the array for a given value and returns the corresponding key if successful
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 38 39 4041 42 43 | function array_search (needle, haystack, argStrict) { // Searches the array for a given value and returns the corresponding key if successful // // version: 1109.2015 // discuss at: http://phpjs.org/functions/array_search // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + input by: Brett Zamir (http://brett-zamir.me) // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // * example 1: array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'}); // * returns 1: 'surname' // * example 2: ini_set('phpjs.return_phpjs_arrays', 'on'); // * example 2: var ordered_arr = array({3:'value'}, {2:'value'}, {'a':'value'}, {'b':'value'}); // * example 2: var key = array_search(/val/g, ordered_arr); // or var key = ordered_arr.search(/val/g); // * returns 2: '3' var strict = !!argStrict, key = ''; if (haystack && typeof haystack === 'object' && haystack.change_key_case) { // Duck-type check for our own array()-created PHPJS_Array return haystack.search(needle, argStrict); } if (typeof needle === 'object' && needle.exec) { // Duck-type for RegExp if (!strict) { // Let's consider case sensitive searches as strict var flags = 'i' + (needle.global ? 'g' : '') + (needle.multiline ? 'm' : '') + (needle.sticky ? 'y' : ''); // sticky is FF only needle = new RegExp(needle.source, flags); } for (key in haystack) { if (needle.test(haystack[key])) { return key; } } return false; } for (key in haystack) { if ((strict && haystack[key] === needle) || (!strict && haystack[key] == needle)) { return key; } } return false; } |
Examples
» Example 1
Running
1 | array_search('zonneveld', {firstname: 'kevin', middle: 'van', surname: 'zonneveld'}); |
Should return
1 | 'surname' |
» Example 2
Running
1 2 3 | ini_set('phpjs.return_phpjs_arrays', 'on'); var ordered_arr = array({3:'value'}, {2:'value'}, {'a':'value'}, {'b':'value'}); var key = array_search(/val/g, ordered_arr); // or var key = ordered_arr.search(/val/g); |
Should return
1 | '3' |
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 array_search goodness in JavaScript.
No comments yet. Be the first!
spread the word:
Use any PHP function in JavaScript
These kind folks have already donated: AYHAN BARI*, Nikita Ekshiyan, Nikita Ekshiyan, Petr Pavel, @HalfWinter, Paulo Freitas, Andros Peña Romo, @andorosu, Raimund Szabo, Nitin Gupta, @nikosdion, Anonymous, Anonymous and Shawn Houser.
<your name here>