Use PHP functions in JavaScript

JavaScript arsort

Sort an array in reverse order and maintain index association

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
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
function arsort (inputArr, sort_flags) {
    // Sort an array in reverse order and maintain index association  
    // 
    // version: 912.1315
    // discuss at: http://phpjs.org/functions/arsort    // +   original 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: The examples are correct, this is a new way
    // %        note 2: Credits to: http://javascript.internet.com/math-related/bubble-sort.html
    // %        note 3: This function deviates from PHP in returning a copy of the array instead
    // %        note 3: of acting by reference and returning true; this was necessary because
    // %        note 3: IE does not allow deleting and re-adding of properties without caching    // %        note 3: of property position; you can set the ini of "phpjs.strictForIn" to true to
    // %        note 3: get the PHP behavior, but use this only if you are in an environment
    // %        note 3: such as Firefox extensions where for-in iteration order is fixed and true
    // %        note 3: property deletion is supported. Note that we intend to implement the PHP
    // %        note 3: behavior by default if IE ever does allow it; only gives shallow copy since    // %        note 3: 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 = arsort(data);
    // *     returns 1: data == {a: 'orange', d: 'lemon', b: 'banana', c: 'apple'}    // *     example 2: ini_set('phpjs.strictForIn', true);
    // *     example 2: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 2: arsort(data);
    // *     results 2: data == {a: 'orange', d: 'lemon', b: 'banana', c: 'apple'}
    // *     returns 2: true    var valArr=[], keyArr=[], k, i, ret, sorter, that = this, strictForIn = false, populateArr = [];
 
    switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a, b) {                return that.strnatcmp(b, a);
            };
            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;
    } 
    var bubbleSort = function (keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i >= 0; i--) {
            for (j = 0; j <= i; j++) {                ret = sorter(inputArr[j+1], inputArr[j]);
                if (ret > 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }        }
    };
 
    // 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; 
 
    // Get key and value arrays
    for (k in inputArr) {
        if (inputArr.hasOwnProperty) {            valArr.push(inputArr[k]);
            keyArr.push(k);
            if (strictForIn) {
                delete inputArr[k];
            }        }
    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);    } catch (e) {
        return false;
    }
 
    // Repopulate the old array    for (i = 0; i < valArr.length; i++) {
        populateArr[keyArr[i]] = valArr[i];
    }
 
    return strictForIn ? true : populateArr;}
external links: original PHP docs | raw js source

Examples

» Example 1

Running

1
2
data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
data = arsort(data);

Should return

1
data == {a: 'orange', d: 'lemon', b: 'banana', c: 'apple'}

» Example 2

Running

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

Should result in

1
data == {a: 'orange', d: 'lemon', b: 'banana', c: 'apple'}

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 arsort 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
25 Jan '09 Permalink

q  @ Brett Zamir: Wow. Amazing work again Brett, you're an unstoppable force.

About strnatcasecmp:
I copied the full list of names for credits. The disclaimer part of the license is already covered by PHP.JS' license, I think. I made a minor change which I think will prevent the arguments to be overwritten.

Everything else is just added, tested and just plain awesome.

Gravatar
Brett Zamir
22 Jan '09 Permalink

q   Ok, now here it is... here's strnatcasecmp and natcasesort (revised to call the former) with an example demonstration. This is based on the algorithm used by PHP, and the strnatcasecmp should include all of the credits/license at http://sourcefrog.net/projects/natsort/natcompare.js (I changed it slightly, just changing to lower case for case-insensitive comparison and shortening parts of the rest of the code somewhat

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
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160
$array1 = {0:'IMG0.png', 1:'img12.png', 2:'img10.png', 3:'img2.png', 4:'img1.png', 5:'IMG3.png'}; 
 
natcasesort($array1);
whatIs($array1)
/* Should be:    0: IMG0.png
    4: img1.png
    3: img2.png
    5: IMG3.png
    2: img10.png    1: img12.png
*/
 
// Depends on strncasecmp
function natcasesort(inputArr) {     var valArr=[], keyArr=[], k, i, ret;
  
    var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i &gt;= 0; i--) {            for (j = 0; j &lt;= i; j++) {
                ret = strnatcasecmp(inputArr[j+1], inputArr[j]);
                if (ret &lt; 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }            }
        }
    };
 
    // Get key and value arrays    for (k in inputArr) {
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k] ;
    }    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);
    } catch(e) {
        return false;    }
 
    // Repopulate the old array
    for (i = 0; i &lt; valArr.length; i++) {
        inputArr[keyArr[i]] = valArr[i];    }
 
    return true;
}
function strnatcasecmp(a,b) {        a = a.toLowerCase();
        b = b.toLowerCase();
 
        function isWhitespaceChar(a) {
                return a.charCodeAt(0) &lt;= 32;        }
 
        function isDigitChar(a) {
                var charCode = a.charCodeAt(0);
                return ( charCode &gt;= 48  &amp;&amp; charCode &lt;= 57 );        }
 
        function compareRight(a,b) {
                var bias = 0;
                var ia = 0;                var ib = 0;
 
                var ca;
                var cb;
                 // The longest run of digits wins.  That aside, the greatest
                // value wins, but we can't know that it will until we've scanned
                // both numbers to know that they have the same magnitude, so we
                // remember it in BIAS.
                for (;; ia++, ib++) {                        ca = a.charAt(ia);
                        cb = b.charAt(ib);
 
                        if (!isDigitChar(ca)
                                        &amp;&amp; !isDigitChar(cb)) {                                return bias;
                        } else if (!isDigitChar(ca)) {
                                return -1;
                        } else if (!isDigitChar(cb)) {
                                return +1;                        } else if (ca &lt; cb) {
                                if (bias == 0) {
                                        bias = -1;
                                }
                        } else if (ca &gt; cb) {                                if (bias == 0)
                                        bias = +1;
                        } else if (ca == 0 &amp;&amp; cb == 0) {
                                return bias;
                        }                }
        }
 
    var ia = 0, ib = 0;
        var nza = 0, nzb = 0;        var ca, cb;
        var result;
 
    while (true) {
        // only count the number of zeroes leading the last number compared        nza = nzb = 0;
 
        ca = a.charAt(ia);
        cb = b.charAt(ib);
         // skip over leading spaces or zeros
        while ( isWhitespaceChar( ca ) || ca =='0' ) {
            if (ca == '0') {
                nza++;
            } else {                // only count consecutive zeroes
                nza = 0;
            }
 
            ca = a.charAt(++ia);        }
 
        while ( isWhitespaceChar( cb ) || cb == '0') {
            if (cb == '0') {
                nzb++;            } else {
                // only count consecutive zeroes
                nzb = 0;
            }
             cb = b.charAt(++ib);
        }
 
        // process run of digits
        if (isDigitChar(ca) &amp;&amp; isDigitChar(cb)) {            if ((result = compareRight(a.substring(ia), b.substring(ib))) != 0) {
                return result;
            }
        }
         if (ca == 0 &amp;&amp; cb == 0) {
            // The strings compare the same.  Perhaps the caller
            // will want to call strcmp to break the tie.
            return nza - nzb;
        } 
        if (ca &lt; cb) {
            return -1;
        } else if (ca &gt; cb) {
            return +1;        }
 
        ++ia; ++ib;
    }
}

Gravatar
Brett Zamir
22 Jan '09 Permalink

q  Sorry, actually my fault.... natcasesort should include strnatcasecmp (which isn't implemented yet) instead of strncasecmp... Then that one should work... :)

Gravatar
Brett Zamir
22 Jan '09 Permalink

q  array_multisort is the only other array function left... (though some other array functions still have to support objects and maybe they need to be reviewed for missing features)...

Gravatar
Brett Zamir
22 Jan '09 Permalink

q   Now the sorting functions can be made complete with my submissions below (and its dependency on strnatcmp--thanks Onno!) and with with SORT_LOCALE patches in my earlier comment:

For asort, arsort, ksort, and sort:

switch (sort_flags) {
case 'SORT_STRING': // compare items as strings
sorter = strnatcmp;
break;

or in the case of krsort and rsort

1
2
3
4
56
switch (sort_flags) {
        case 'SORT_STRING': // compare items as strings
            sorter = function (a,b) {
                    return strnatcmp(b,a);
            }            break;


FYI, PHP's own algorithm for sorting naturally is available in a JavaScript function (but not a case-sensitive version) at http://sourcefrog.net/projects/natsort/natcompare.js . I presume yours is just as good, Onno, and seems to work just fine, but for your reference, it's there in case you think you may have missed something.

We can also get natsort as a derivative of asort, also using strnatcmp (but don't be thrown off by the fact that this function (and natcasesort discussed below) are supposed to preserve keys, and as such won't be able to make a difference with JavaScript arrays as they are expected to be passed by reference--but they will work with ).

The following depends on strnatcmp which depends on strcmp:

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
50
$array1 = {a:&quot;img12.png&quot;, b:&quot;img10.png&quot;, c:&quot;img2.png&quot;, d:&quot;img1.png&quot;};
natsort($array1);
/*
d: img1.png
c: img2.pngb: img10.png
a: img12.png
*/
 
 function natsort(inputArr) { 
    var valArr=[], keyArr=[], k, i, ret;
  
    var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;        for (i = inputArr.length-2; i &gt;= 0; i--) {
            for (j = 0; j &lt;= i; j++) {
                ret = strnatcmp(inputArr[j+1], inputArr[j]);
                if (ret &lt; 0) {
                    tempValue = inputArr[j];                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];
                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;                }
            }
        }
    };
     // Get key and value arrays
    for (k in inputArr) {
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k] ;    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr);
    } catch(e) {        return false;
    }
 
    // Repopulate the old array
    for (i = 0; i &lt; valArr.length; i++) {        inputArr[keyArr[i]] = valArr[i];
    }
 
    return true;
}


Now I'm fairly certain natcasesort should work as follows, but I believe there must be a bug in strncasecmp (which returns 0 at each iteration), since it isn't working:

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
$array1 = {a:'IMG0.png', b:'img12.png', c:'img10.png', d:'img2.png', e:'img1.png', f:'IMG3.png'}; 
natcasesort($array1);
/* Should be:
    0: IMG0.png
    4: img1.png    3: img2.png
    5: IMG3.png
    2: img10.png
    1: img12.png
*/ 
// Depends on strncasecmp
function natcasesort(inputArr) { 
    var valArr=[], keyArr=[], k, i, ret;
      var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;
        for (i = inputArr.length-2; i &gt;= 0; i--) {
            for (j = 0; j &lt;= i; j++) {
                ret = strncasecmp(inputArr[j+1], inputArr[j]);                if (ret &lt; 0) {
                    tempValue = inputArr[j];
                    inputArr[j] = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal = keyArr[j];                    keyArr[j] = keyArr[j+1];
                    keyArr[j+1] = tempKeyVal;
                }
            }
        }    };
 
    // Get key and value arrays
    for (k in inputArr) {
        valArr.push(inputArr[k]);        keyArr.push(k);
        delete inputArr[k] ;
    }
    try {
        // Sort our new temporary arrays        bubbleSort(keyArr, valArr);
    } catch(e) {
        return false;
    }
     // Repopulate the old array
    for (i = 0; i &lt; valArr.length; i++) {
        inputArr[keyArr[i]] = valArr[i];
    }
     return true;
}

Gravatar
Brett Zamir
18 Jan '09 Permalink

q   Sorry, in rsort(), I neglected to add a variable declaration for 'sorter' at the top, so it is a global now.

On the good side, I figured out there is an easy way to get to sort by the locale, though there's apparently no way in regular JavaScript to change the locale, as there is in PHP.

You can replace the SORT_STRING and SORT_LOCALE_STRING in all sort functions (except for usort, uksort, uasort which don't have them) now with the following:

(for krsort and rsort only:)

1
2
3
4
56
7
case 'SORT_STRING': // compare items as strings
                        throw 'Not implemented yet';
                case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale
                        sorter = function (a, b) {
                                return(b.localeCompare(a));                        };
                        break;


For asort, arsort, ksort, and sort:

1
2
3
4
56
7
case 'SORT_STRING': // compare items as strings
                        throw 'Not implemented yet';
                case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale
                        sorter = function (a, b) {
                                return(a.localeCompare(b));                        };
                        break;

Gravatar
Kevin van Zonneveld
17 Jan '09 Permalink

q  @ Brett Zamir: Wicked!

Gravatar
Brett Zamir
17 Jan '09 Permalink

q   Sorry... the sort() and rsort() I just updated can be used, but asort() needs to be fixed to the following, and I forgot arsort():

function asort(inputArr, sort_flags) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir
// % note: The examples are correct, this is a new way
// % note: Credits to: http://javascript.internet.com/math-related/bubble-sort.html
// * example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
// * example 1: asort(data);
// * results 1: data == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'}
// * returns 1: true

var valArr=[], keyArr=[], k, i, ret, sorter;

switch (sort_flags) {
case 'SORT_STRING': // compare items as strings
case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6)
throw 'Not implemented yet';
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;
}

var bubbleSort = function(keyArr, inputArr) {
var i, j, tempValue, tempKeyVal;
for (i = inputArr.length-2; i >= 0; i--) {
for (j = 0; j <= i; j++) {
ret = sorter(inputArr[j+1], inputArr[j]);
if (ret < 0) {
tempValue = inputArr[j];
inputArr[j] = inputArr[j+1];
inputArr[j+1] = tempValue;
tempKeyVal = keyArr[j];
keyArr[j] = keyArr[j+1];
keyArr[j+1] = tempKeyVal;
}
}
}
};

// Get key and value arrays
for (k in inputArr) {
valArr.push(inputArr[k]);
keyArr.push(k);
delete inputArr[k] ;
}
try {
// Sort our new temporary arrays
bubbleSort(keyArr, valArr);
} catch(e) {
return false;
}

// Repopulate the old array
for (i = 0; i < valArr.length; i++) {
inputArr[keyArr[i]] = valArr[i];
}

return true;
}

function arsort(inputArr, sort_flags) {
// http://kevin.vanzonneveld.net
// + original by: Brett Zamir
// % note: The examples are correct, this is a new way
// % note: Credits to: http://javascript.internet.com/math-related/bubble-sort.html
// * example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
// * example 1: asort(data);
// * results 1: data == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'}
// * returns 1: true

var valArr=[], keyArr=[], k, i, ret, sorter;

switch (sort_flags) {
case 'SORT_STRING': // compare items as strings
case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with i18n_loc_set_default() as of PHP6)
throw 'Not implemented yet';
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;
}

var bubbleSort = function(keyArr, inputArr) {
var i, j, tempValue, tempKeyVal;
for (i = inputArr.length-2; i >= 0; i--) {
for (j = 0; j <= i; j++) {
ret = sorter(inputArr[j+1], inputArr[j]);
if (ret > 0) {
tempValue = inputArr[j];
inputArr[j] = inputArr[j+1];
inputArr[j+1] = tempValue;
tempKeyVal = keyArr[j];
keyArr[j] = keyArr[j+1];
keyArr[j+1] = tempKeyVal;
}
}
}
};

// Get key and value arrays
for (k in inputArr) {
valArr.push(inputArr[k]);
keyArr.push(k);
delete inputArr[k] ;
}
try {
// Sort our new temporary arrays
bubbleSort(keyArr, valArr);
} catch(e) {
return false;
}

// Repopulate the old array
for (i = 0; i < valArr.length; i++) {
inputArr[keyArr[i]] = valArr[i];
}

return true;
}

[/CODE]

Gravatar
Brett Zamir
17 Jan '09 Permalink

q   Sorry not to think of it earlier... Here are asort() and arsort() updated with sort_flags infrastructure and SORT_REGULAR added.

SORT_STRING (as well as natsort and natcasesort) might also be integrated into all of these functions by adapting the code at http://sourcefrog.net/projects/natsort/natcompare.js (note that the URL is not a typo), but I don't know how you want to do it (and it would need a little tweaking, at least for case insensitive sorts, but it is based on the same algorithm used by PHP).

I've also copied the same infrastructure for sort(), and rsort() (and sped up 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
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
9091
92
93
94
9596
97
98
99
100101
102
103
104
105106
107
108
109
110111
112
113
114
115116
117
118
119
120121
122
123
124
125126
127
128
129
130131
132
133
134
135136
137
138
139
140141
142
143
144
145146
147
148
149
150151
152
153
154
155156
157
158
159
160161
162
163
164
165
function asort(inputArr, sort_flags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Brett Zamir
    // %          note: The examples are correct, this is a new way
    // %          note: Credits to: http://javascript.internet.com/math-related/bubble-sort.html     // *     example 1: data = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 1: asort(data);
    // *     results 1: data == {c: 'apple', b: 'banana', d: 'lemon', a: 'orange'}
    // *     returns 1: true
                var valArr=[], keyArr=[], k, i, ret, sorter;
 
        switch (sort_flags) {
                case 'SORT_STRING': // compare items as strings
                case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)                        throw 'Not implemented yet';
                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 &gt; b)                                        return 1;
                                if (a &lt; b)
                                        return -1;
                                return 0;
                        };                        break;
        }
 
    var bubbleSort = function(keyArr, inputArr) {
        var i, j, tempValue, tempKeyVal;        for (i = inputArr.length-2; i &gt;= 0; i--) {
            for (j = 0; j &lt;= i; j++) {
                ret = sorter(inputArr[j+1], inputArr[j]);
                if (ret &gt; 0) {
                    tempValue     = inputArr[j];                    inputArr[j]   = inputArr[j+1];
                    inputArr[j+1] = tempValue;
                    tempKeyVal    = keyArr[j];
                    keyArr[j]     = keyArr[j+1];
                    keyArr[j+1]   = tempKeyVal;                }
            }
        }
    };
      // Get key and value arrays
    for (k in inputArr) { 
        valArr.push(inputArr[k]);
        keyArr.push(k);
        delete inputArr[k] ;    }
    try {
        // Sort our new temporary arrays
        bubbleSort(keyArr, valArr); 
    } catch(e) {        return false;
    }
 
    // Repopulate the old array
    for (i = 0; i &lt; valArr.length; i++) {          inputArr[keyArr[i]] = valArr[i];
    }
    
    return true;
} 
function sort (inputArr, sort_flags) {
    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir    // *     example 1: sort(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true
    // *     example 2: fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 2: sort(fruits);
    // *     returns 2: true    // *     results 2: fruits == {0: 'apple', 1: 'banana', 2: 'lemon', 3: 'orange'}
 
    var valArr = [], keyArr=[];
    var k = '', i = 0;
        for (k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);
        delete inputArr[k] ;
    }
                switch (sort_flags) {
                case 'SORT_STRING': // compare items as strings
                case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)
                        throw 'Not implemented yet';
                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 &gt; b)
                                        return 1;
                                if (a &lt; b)                                        return -1;
                                return 0;
                        };
                        break;
        }    valArr.sort(sorter);
 
    for (i = 0; i &lt; valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];
    }    return true;
}
 
 
function rsort (inputArr, sort_flags) {    // http://kevin.vanzonneveld.net
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: Brett Zamir
    // *     example 1: rsort(['Kevin', 'van', 'Zonneveld']);
    // *     returns 1: true    // *     example 2: fruits = {d: 'lemon', a: 'orange', b: 'banana', c: 'apple'};
    // *     example 2: rsort(fruits);
    // *     returns 2: true
    // *     results 2: fruits == {0: 'orange', 1: 'lemon', 2: 'banana', 3: 'apple'}
     var valArr = [], keyArr=[];
    var k = '', i = 0;
    
    for (k in inputArr) { // Get key and value arrays
        valArr.push(inputArr[k]);        delete inputArr[k] ;
    }
 
    switch (sort_flags) {
                case 'SORT_STRING': // compare items as strings                case 'SORT_LOCALE_STRING': // compare items as strings, based on the current locale (set with  i18n_loc_set_default() as of PHP6)
                        throw 'Not implemented yet';
                case 'SORT_NUMERIC': // compare items numerically
                        sorter = function (a, b) {
                                return(b - a);                        };
                        break;
                case 'SORT_REGULAR': // compare items normally (don't change types)
                default:
                        sorter = function (a, b) {                                if (a &lt; b)
                                        return 1;
                                if (a &gt; b)
                                        return -1;
                                return 0;                        };
                        break;
        }
    valArr.sort(sorter);
     for (i = 0; i &lt; valArr.length; i++) { // Repopulate the old array
        inputArr[i] = valArr[i];
    }
    return true;
}


Contribute a New function

Download

Download

There is a wide variety of packages if the default doesn't suit you.
You can also compile your own package to avoid any overhead.

Support us

spread the word:


Use any PHP function in JavaScript


These kind folks have already donated: Anonymous and Shawn Houser.
<your name here>

Click here to lend your support to: phpjs and make a donation at www.pledgie.com !

RSS

Tweets

Comments

Who uses php.js

If you use php.js, let us know and get linked.

Progress

php.js is complete for 83.7%

php.js on

Discuss php.js' future at Google Groups
Help improve php.js on github



Powered by php.js
Stats