Last active
August 29, 2015 13:58
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var itemsTweak = { | |
toArray: function(obj){ | |
var arr = []; | |
for(i in obj)arr.push(obj[i]); | |
return arr; | |
}, | |
sortBy: function(arr,key,way){ | |
if(arr.length == 0)return []; | |
arr = arr.sort(function(a, b) { | |
var k1=a[key].toLowerCase(), k2=b[key].toLowerCase(); | |
if (k1 < k2)return -1 | |
if (k1 > k2)return 1 | |
return 0 | |
}); | |
if(way){ | |
if(way>0){ | |
if(arr[0][key]>arr[arr.length-1][key])arr = arr.reverse(); | |
} | |
if(way<0){ | |
if(arr[0][key]<arr[arr.length-1][key])arr = arr.reverse(); | |
} | |
} | |
console.log(JSON.stringify(arr)) | |
return arr | |
}, | |
/** | |
* Description | |
* @method getSorted | |
* @param {} obj: Object to be sorted | |
* @param {} key: key to be used as reference in sorting | |
* @param {} way: <0: descending, >0: ascending, 0 or undefined: no reverse will be applied | |
*/ | |
getSorted: function(obj,key,way){ | |
return itemsTweak.sortBy(itemsTweak.toArray(obj),key,way); | |
} | |
}; | |
var sampleObj = { | |
"key1234": { | |
"name": "abc" | |
}, | |
"key157856": { | |
"name": "ghi" | |
}, | |
"key21256877": { | |
"name": "def" | |
}, | |
"key2125687rtrt7": { | |
"name": "bgc" | |
} | |
}; | |
var myObjectSorted = itemsTweak.getSorted(sampleObj,'name',1); | |
document.write(JSON.stringify(myObjectSorted)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment