Use PHP functions in JavaScript

JavaScript sort

Sort an 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
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
function sort (inputArr, sort_flags) {
    // Sort an array  
    // 
    // version: 912.1315
    // discuss at: http://phpjs.org/functions/sort    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir (http://brett-zamir.me)
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // %        note 1: SORT_STRING (as well as natsort and natcasesort) might also be
    // %        note 1: integrated into all of these functions by adapting the code at    // %        note 1: http://sourcefrog.net/projects/natsort/natcompare.js
    // %        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: sort(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: ['Kevin', 'Zonneveld', 'van']
    // *     example 2: ini_set('phpjs.strictForIn', true);
    // *     example 2: fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};    // *     example 2: sort(fruits);
    // *     results 2: fruits == {0: 'apple', 1: 'banana', 2: 'lemon', 3: 'orange'}
    // *     returns 2: true
    var valArr = [], keyArr=[], k = '', i = 0, sorter = false, 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;
    }
 
    // 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;
 
    for (k in inputArr) { // Get key and value arrays
        if (inputArr.hasOwnProperty) {
            valArr.push(inputArr[k]);            if (strictForIn) {
                delete inputArr[k];
            }
        }
    } 
    valArr.sort(sorter);
 
    for (i = 0; i < valArr.length; i++) { // Repopulate the old array
        populateArr[i] = valArr[i];    }
    return strictForIn ? true : populateArr;
}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
sort(['Kevin', 'van', 'Zonneveld']);

Should return

1
['Kevin', 'Zonneveld', 'van']

» Example 2

Running

1
2
3
ini_set('phpjs.strictForIn', true);
fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
sort(fruits);

Should result in

1
fruits == {0: 'apple', 1: 'banana', 2: 'lemon', 3: 'orange'}

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 sort goodness in JavaScript.

Comments

Add Comment
Use:
[CODE]
your_stuff('here');
[/CODE]
for proper code formatting
By submitting code here you are allowing us to use it in php.js hence dual licensing it under the MIT and GPL licenses

Gravatar
Kevin van Zonneveld
16 Jan '09 Permalink

q   @ Brett Zamir: What a beautiful moment it is, when I paste one of your functions, write a testcase, click on 'Play', and see:

[CODE="text"]
Test result
===========================================================================
array/uasort.js results#1 OKAY
[/CODE]

That word 'OKAY' is like a little present :) You are awesome Brett.

Gravatar
Brett Zamir
16 Jan '09 Permalink

q  Grrrr. Sorry, the 'i' for loop (in sort(), rsort(), and usort() need to have 'var' added in front)--accidental globals... Thx, Brett

Gravatar
Brett Zamir
16 Jan '09 Permalink

q   Actually, please just use this one for usort() instead, as I needed to allow the callback as string. There's also another array implementation: uasort().

1
2
3
4
56
7
8
9
1011
12
13
14
1516
17
18
19
2021
22
23
24
2526
27
function usort (inputArr, sorter) {
    if (typeof sorter === 'string') {
        sorter = this[sorter];
    }
    else if (sorter instanceof Array) {        sorter = this[sorter[0]][sorter[1]];
    }
    var valArr = [], keyArr=[];
    for (var k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);        delete inputArr[k] ;
    }
    try {
        valArr.sort(sorter);
    } catch (e) {        return false;
    }
    for (i=0; i &lt; valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];
    }    return true;
}
 
$stuff = {&quot;d&quot; : &quot;3&quot;, &quot;a&quot; : &quot;1&quot;, &quot;b&quot; : &quot;11&quot;, &quot;c&quot; : &quot;4&quot;};
usort($stuff, function (a, b) {            return(a-b);
});



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
function uasort (inputArr, sorter) {
    if (typeof sorter === 'string') {
        sorter = this[sorter];
    }
    else if (sorter instanceof Array) {                sorter = this[sorter[0]][sorter[1]];
    }   
    var valArr = [], keyArr=[], tempKeyVal, tempValue, ret;
 
    var sorterNew = function (keyArr, valArr) {                for (var i=valArr.length-2; i &gt;=0; i--) {
                        for (var j=0; j &lt;= i; j++) {
                                ret = sorter(valArr[j+1], valArr[j]);
                                if (ret &lt; 0) {
                                        tempValue = valArr[j];                                        valArr[j] = valArr[j+1];
                                        valArr[j+1] = tempValue;
                                        tempKeyVal = keyArr[j];
                                        keyArr[j] = keyArr[j+1];
                                        keyArr[j+1] = tempKeyVal;                                }
                        }
                }
    }
     for (var k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k] ;
    }    try {
        sorterNew(keyArr, valArr); // Sort our new temporary arrays
    }
    catch(e) {
        return false;    }
    for (i=0; i &lt; valArr.length; i++) { // Repopulate the old array
        inputArr[keyArr[i]] = valArr[i];
    }
    return true;}
 
$fruits = {&quot;d&quot; : &quot;lemon&quot;, &quot;a&quot; : &quot;orange&quot;, &quot;b&quot; : &quot;banana&quot;, &quot;c&quot; : &quot;apple&quot;};
uasort($fruits, function (a, b) {
  if (a &gt; b)    return 1;
  if (a &lt; b)
    return -1;
  return 0;
});var $output = '';
for (var $key in $fruits) {
    $val = $fruits[$key];
    $output += $key+' = '+$val+&quot;\n&quot;;
}alert($output);
 
/*
c = apple
b = bananad = lemon
a = orange
*/

Gravatar
Brett Zamir
16 Jan '09 Permalink

q  Sorry, forgot to rename the last one to usort()!

Gravatar
Brett Zamir
16 Jan '09 Permalink

q   Here's sort(), rsort(), and usort() which now support objects (though no additions of sorting types for sort() or rsort()):

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 sort (inputArr, sort_flags) {
    var valArr = [], keyArr=[];
    for (var k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        delete inputArr[k] ;    }
 
    var 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);        };
    }
    if (sorter !== false) {
        valArr.sort(sorter);
    } else {        valArr.sort();
    }
 
    for (i=0; i &lt; valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];    }
    return true;
}
$fruits = {&quot;d&quot; : &quot;lemon&quot;, &quot;a&quot; : &quot;orange&quot;, &quot;b&quot; : &quot;banana&quot;, &quot;c&quot; : &quot;apple&quot;};
sort($fruits); 
var $output = '';
for (var $key in $fruits) {
    $val = $fruits[$key];
    $output += $key+' = '+$val+&quot;\n&quot;;}
alert($output);
/*
0 = apple
1 = banana2 = lemon
3 = orange
*/


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
function rsort (inputArr, sort_flags) {
    var valArr = [], keyArr=[];
    for (var k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        delete inputArr[k] ;    }
 
    var 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(b - a);        };
    }
    if (sorter !== false) {
        valArr.sort(sorter);
    } else {        valArr.sort();
        valArr.reverse();
    }
 
    for (i=0; i &lt; valArr.length; i++) { // Repopulate the old array        inputArr[i] = valArr[i];
    }
    return true;
}
$fruits = {&quot;d&quot; : &quot;lemon&quot;, &quot;a&quot; : &quot;orange&quot;, &quot;b&quot; : &quot;banana&quot;, &quot;c&quot; : &quot;apple&quot;};//$fruits = [&quot;lemon&quot;, &quot;orange&quot;, &quot;banana&quot;, &quot;apple&quot;];
// $fruits = {&quot;d&quot; : &quot;3&quot;, &quot;a&quot; : &quot;1&quot;, &quot;b&quot; : &quot;11&quot;, &quot;c&quot; : &quot;4&quot;};
rsort($fruits);
// rsort($fruits, 'SORT_NUMERIC');
 var $output = '';
for (var $key in $fruits) {
    $val = $fruits[$key];
    $output += $key+' = '+$val+&quot;\n&quot;;
}alert($output);
/* 
0 = orange
1 = lemon
2 = banana3 = apple
*/



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
function sort (inputArr, sorter) {
    var valArr = [], keyArr=[];
    for (var k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        delete inputArr[k] ;    }
    try {
        valArr.sort(sorter);
    } catch (e) {
        return false;    }
    for (i=0; i &lt; valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];
    }
    return true;}
 
$stuff = {&quot;d&quot; : &quot;3&quot;, &quot;a&quot; : &quot;1&quot;, &quot;b&quot; : &quot;11&quot;, &quot;c&quot; : &quot;4&quot;};
sort($stuff, function (a, b) {
            return(a-b);});
 
var $output = '';
for (var $key in $stuff) {
    $val = $stuff[$key];    $output += $key+' = '+$val+&quot;\n&quot;;
}
alert($output);
/*
0 = 11 = 3
2 = 4
3 = 11
*/


Contribute a New function