Sort Objects By A Property Values
I have some objects in an array and want to have them sorted. The objects should be sorted by a metric value. So I have the following function: objectz.sort(function(a,b){
Solution 1:
objectz.sort(function(a,b){
var result = b.metric - a.metric;
if (!result) return a.name > b.name ? 1 : -1;
return result;
});
Solution 2:
Similar to zerkms:
objectz.sort(function(a,b) {
var x = b.metric - a.metric;
return x || b.name - a.name;
});
Seems to be a reverse sort (higher values occur first), is that what you want?
Edit
Note that the -
operator is only suitable if the value of 'name' can be converted to a number. Otherwise, use <
or >
. The sort function should deal with a.name == b.name, which the >
opertator on its own won't do, so you need something like:
objectz.sort(function(a,b) {
var x = b.metric - a.metric;
// If b.metric == a.metricif (!x) {
if (b.name == a.name) {
x = 0;
elseif (b.name < a.name) {
x = 1;
else {
x = -1;
}
}
return x;
});
which can be made more concise:
objectz.sort(function(a,b) {
var x = b.metric - a.metric;
if (!x) {
x = (b.name == a.name)? 0 : (b.name < a.name)? 1 : -1;
}
return x;
});
Given that the metric
comparison seems to be largest to smallest order, then the ternary exrpession should be:
x = (b.name == a.name)? 0 : (b.name < a.name)? -1 : 1;
if it is required that say Zelda comes before Ann. Also, the value of name
should be reduced to all lower case (or all upper case), otherwise 'zelda' and 'Ann' will be sorted in the opposite order to 'Zelda' and 'ann'
Post a Comment for "Sort Objects By A Property Values"