I a data structure shaped like
[{name:"kevin",major:1, minor:2}]
How would I sort a list of these objects if I wanted them to be sorted such that they the majors are in order and the minors are sorted secondarily?
I a data structure shaped like
[{name:"kevin",major:1, minor:2}]
How would I sort a list of these objects if I wanted them to be sorted such that they the majors are in order and the minors are sorted secondarily?
Just define a sort callback.
var myData = [{ name: "kevin", major: 1, minor: 2 }, { name: "bob", major: 1, minor: 1 }, { name: "dave", major: 2, minor: 1 }, { name: "john", major: 2, minor: 2 }];
myData.sort(function (a, b) {
return a.major - b.major || a.minor - b.minor;
});
document.write('<pre>' + JSON.stringify(myData, 0, 4) + '</pre>');
Here you go:
var myData = [{
name: "kevin",
major: 1,
minor: 2
}, {
name: "bob",
major: 1,
minor: 1
}, {
name: "dave",
major: 2,
minor: 1
}, {
name: "john",
major: 2,
minor: 2
}];
var mySort = function(a, b) {
if (a.major == b.major) {
return a.minor - b.minor;
} else {
return a.major - b.major;
}
};
document.getElementById("results").innerHTML = JSON.stringify(myData.sort(mySort));
<div id="results"></div>