Home >Web Front-end >JS Tutorial >3 examples of javascript sorting JSON data_javascript skills
1. Suitable for numerical sorting and subtitle sorting
There are many json sorting methods, and this is the simplest one.
Copy code
function JsonSort(json ,key){
//console.log(json);
for(var j=1,jl=json.length;j < jl;j ){
var temp = json[j] ,
val = temp[key],
i = j-1;
while(i >=0 && json[i][key]>val){
json[i 1 ] = json[i];
i = i-1;
}
json[i 1] = temp;
}
//console.log(json);
return json;
}
var json = JsonSort(willSort,'age');
console.log(json);
3. JSON sorting example 3
Copy code
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key]; var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
people = sortByKey(people, 'name');