Sort by keys in JS
To sort by keys, you first have to collect the keys in an array, then sort the array, and finally create a new object by copying the data from the original one in the order of the sorted array. Well, I provided a function that also may sort the keys not alphabetically, but in a user-specified order, similarly to MySQL's ORDER BY FIELD.
var sortByKeys: function(arr, fields) {
var keys = [];
for (var key in arr) {
if (arr.hasOwnProperty(key)) {
keys.push(key);
}
}
if (typeof fields !== 'undefined') {
keys.sort(function(a, b){
return fields.indexOf(a) - fields.indexOf(b);
});
} else {
keys.sort();
}
data = {};
for (var i = 0, l = keys.length; i < l; i += 1) {
var key = keys[i];
data[key] = arr[key];
}
return data;
}Written by Maxim Krizhanovsky
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Javascript
Authors
Did you know?
JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.
Security insights from Cside
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#