JavaScript ksort
Sort an array by key
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 44 4546 47 48 49 5051 52 53 54 5556 57 58 59 6061 62 63 64 6566 67 68 69 7071 72 73 74 7576 77 78 79 8081 82 83 84 8586 87 88 89 90 | function ksort (inputArr, sort_flags) { // Sort an array by key // // version: 912.1315 // discuss at: http://phpjs.org/functions/ksort // + original by: GeekFG (http://geekfg.blogspot.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // + improved by: Brett Zamir (http://brett-zamir.me) // % note 1: The examples are correct, this is a new way // % note 2: This function deviates from PHP in returning a copy of the array instead // % note 2: of acting by reference and returning true; this was necessary because // % note 2: IE does not allow deleting and re-adding of properties without caching // % note 2: of property position; you can set the ini of "phpjs.strictForIn" to true to // % note 2: get the PHP behavior, but use this only if you are in an environment // % note 2: such as Firefox extensions where for-in iteration order is fixed and true // % note 2: property deletion is supported. Note that we intend to implement the PHP // % note 2: behavior by default if IE ever does allow it; only gives shallow copy since // % note 2: is by reference in PHP anyways // - depends on: i18n_loc_get_default // * example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'}; // * example 1: data = ksort(data); // * results 1: {a: 'orange', b: 'banana', c: 'apple', d: 'lemon'} // * example 2: ini_set('phpjs.strictForIn', true); // * example 2: data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'}; // * example 2: ksort(data); // * results 2: data == {1: 'Kevin', 2: 'van', 3: 'Zonneveld'} // * returns 2: true var tmp_arr={}, keys=[], sorter, i, k, that=this, strictForIn = false, populateArr = []; switch (sort_flags) { case 'SORT_STRING': // compare items as strings sorter = function (a, b) { return that.strnatcmp(a, b); }; break; case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6) var loc = this.i18n_loc_get_default(); sorter = this.php_js.i18nLocales[loc].sorting; break; case 'SORT_NUMERIC': // compare items numerically sorter = function (a, b) { return (a - b); }; break; case 'SORT_REGULAR': // compare items normally (don't change types) default: sorter = function (a, b) { if (a > b) { return 1; } if (a < b) { return -1; } return 0; }; break; } // Make a list of key names for (k in inputArr) { if (inputArr.hasOwnProperty) { keys.push(k); } } keys.sort(sorter); // BEGIN REDUNDANT this.php_js = this.php_js || {}; this.php_js.ini = this.php_js.ini || {}; // END REDUNDANT strictForIn = this.php_js.ini['phpjs.strictForIn'] && this.php_js.ini['phpjs.strictForIn'].local_value; populateArr = strictForIn ? inputArr : populateArr; // Rebuild array with sorted key names for (i = 0; i < keys.length; i++) { k = keys[i]; tmp_arr[k] = inputArr[k]; if (strictForIn) { delete inputArr[k]; } } for (i in tmp_arr) { if (tmp_arr.hasOwnProperty) { populateArr[i] = tmp_arr[i]; } } return strictForIn ? true : populateArr; } |
Examples
» Example 1
Running
1 2 | data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'}; data = ksort(data); |
Should result in
1 | {a: 'orange', b: 'banana', c: 'apple', d: 'lemon'} |
» Example 2
Running
1 2 3 | ini_set('phpjs.strictForIn', true); data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'}; ksort(data); |
Should result in
1 | data == {1: 'Kevin', 2: 'van', 3: 'Zonneveld'} |
Dependencies
In order to use this function, you also need:
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 ksort goodness in JavaScript.
Lastly for now (I hope), sort() and rsort() (and usort()) need to be changed along the lines of asort() (and uasort()) to allow object sorting...
Sorry, I guess that wasn't all. You can also get arsort() by changing this line in asort():
1 | if (inputArr[j+1] < inputArr[j]) { |
to
1 | if (inputArr[j+1] > inputArr[j]) { |
And we can also trivially get usort() and uksort() by changing sort flags in the corresponding functions to callbacks (uasort() would not be as easy though, since my version presently depends on the sorter for internal uses as well):
1 2 3 4 56 7 8 9 1011 | function usort( array, sorter ) { if (typeof sorter === 'string') { sorter = window[sorter]; } if (sorter !== false) { array.sort(sorter); } else { array.sort(); } return true;} |
and
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 | function uksort(array, sorter) { if (typeof sorter === 'string') { sorter = window[sorter]; } var tmp_arr = {}, keys = []; // Make a list of key names for (var key in array) { keys.push(key); } // Sort key names try { if (sorter) { keys.sort(sorter); } else { keys.sort(); } } catch (e) { return false; } // Rebuild array with sorted key names for (var i = 0; i < keys.length; i++) { key = keys[i]; tmp_arr[key] = array[key]; delete array[key]; } for (i in tmp_arr) { array[i] = tmp_arr[i] } return true; } var arr = {"d" : "lemon", "a" : "orange", "b" : "banana", "c" : "apple"}; uksort(arr, function (a, b) { if (a > b) return 1; if (b < a) return -1; return 0; }); |
The only other array functions left (besides uasort() as mentioned above) now are natsort, natcasesort, and array_multisort. (Of course, we have to still support the flags on the existing ones, etc.)
Lastly, while it looks like your other sort functions are fine, krsort() does need to be changed too. For that, you can use the ksort() I sent two posts before with the line "keys.reverse();" added after the try-catch block.
Whoops, sorry the function just given works, but the example doesn't! (I was playing around with the values and forgot to switch back). The example section should be:
1 2 3 4 56 7 8 9 1011 12 13 14 | $fruits = {"d" : "lemon", "a" : "orange", "b" : "banana", "c" : "apple"}; asort($fruits); var $output = ''; for (var $key in $fruits) { $val = $fruits[$key]; $output += $key+' = '+$val+"\n"; } alert($output); /* c = appleb = banana d = lemon a = orange */ |
I also used the same basic approach just mentioned in this asort() as well, but I needed a slightly different approach since I could not rely on values being unique, as keys were for ksort().
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 44 4546 | function asort (inputArr) { function bubbleSort(keyArr, inputArr) { for (var i = inputArr.length-2; i >= 0; i--) { for (var j=0; j <= i; j++) { if (inputArr[j+1] < inputArr[j]) { var tempValue = inputArr[j]; inputArr[j] = inputArr[j+1]; inputArr[j+1] = tempValue; var tempKeyVal = keyArr[j]; keyArr[j] = keyArr[j+1]; keyArr[j+1] = tempKeyVal; } } } } var valArr = [], keyArr=[]; for (var k in inputArr) { // Get key and value arrays valArr.push(inputArr[k]); keyArr.push(k); delete inputArr[k] ; } try { bubbleSort(keyArr, valArr); // Sort our new temporary arrays } catch(e) { return false; } for (i=0; i < valArr.length; i++) { // Repopulate the old array inputArr[keyArr[i]] = valArr[i]; } return true; } $fruits = {"d" : "lemon", "a" : "orange", "b" : "orange", "c" : "orange"}; asort($fruits); var $output = '';for (var $key in $fruits) { $val = $fruits[$key]; $output += $key+' = '+$val+"\n"; } alert($output);/* c = apple b = banana d = lemon a = orange*/ |
Hi,
I don't think that this function is working. The last line does not replace the array, since in JavaScript, as a whole object, the arrays (though their values are passed in by reference), are passed in by value (you cannot, for example, reassign or delete the passed-in array as a whole).
You can confirm this with something like this:
1
2
3
4
56
| function changeArr (arr) { arr = [3, 2, 1]; } var a = [1, 2, 3]; changeArr(a);alert(a); // still 1, 2, 3 |
However, you can delete and then rebuild its contents, modifying the function as such:
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 44 4546 47 48 49 | function ksort(array, sort_flags) { // http://kevin.vanzonneveld.net // + original by: GeekFG (http://geekfg.blogspot.com) // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // % note: The examples are correct, this is a new way // * example 1: data = {2: 'van', 3: 'Zonneveld', 1: 'Kevin'}; // * example 1: ksort(data); // * results 1: data == {1: 'Kevin', 2: 'van', 3: 'Zonneveld'} // * returns 1: true var tmp_arr = {}, keys = [], sorter = false; // For now only SORT_NUMERIC has a custom sorter // and SORT_REGULAR, SORT_STRING, and SORT_LOCALE_STRING // are all handled with the default sorter if (sort_flags == 'SORT_NUMERIC') { sorter = function (a, b) { return(a - b); }; } // Make a list of key names for (var key in array) { keys.push(key); } // Sort key names try { if (sorter !== false) { keys.sort(sorter); } else { keys.sort(); } } catch (e) { return false; } // Rebuild array with sorted key names for (var i = 0; i < keys.length; i++) { key = keys[i]; tmp_arr[key] = array[key]; delete array[key]; } for (i in tmp_arr) { array[i] = tmp_arr[i] } return true; } |


Brett Zamir
18 Jan '09
A better solution to the latter problem has been DHA (in omega-3 fatty acids, especially fish oil), and that has also been just awesome for working memory (though I think it can be a little dehydrating to take it every day). I really think there are inadequacies in our food supply, with current farming practices only replenishing the soil with the nutrients needed for mere growth (like nitrogen), from what I've heard.
Just heard a TV special about how a particularly long-lived group of Asians lived longer due to vitamins in their soil or something (the special was in Chinese (I'm living in China), and my Chinese is still just so-so).
Now how's that for really off-topic?