I have a very simple JSON object like the following:
{
\"people\":[
{
\"f_name\":\"john\",
\"l_name\":\"doe\",
\"sequence
Demo: https://jsfiddle.net/kvxazhso/
Successfully pass equal values (keep same order). Flexible : handle ascendant (123) or descendant (321), works for numbers, letters, and unicodes. Works on all tested devices (Chrome, Android default browser, FF).
Given data such :
var people = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 3 },
{ 'myKey': 'C', 'status': 3 },
{ 'myKey': 'D', 'status': 2 },
{ 'myKey': 'E', 'status': 7 },
...
];
Sorting by ascending or reverse order:
function sortJSON(arr, key, way) {
return arr.sort(function(a, b) {
var x = a[key]; var y = b[key];
if (way === '123') { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }
if (way === '321') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }
});
}
people2 = sortJSON(people,'status', '321'); // 123 or 321
alert("2. After processing (0 to x if 123; x to 0 if 321): "+JSON.stringify(people2));