Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
160 views
in Technique[技术] by (71.8m points)

Sort JavaScript array of Objects by two properties and given order

I have this JavaScript array of Objects:

data = [
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
]

and I would like to sort it both by 'provider' (the three "This" before the three "All") and by 'measure' (first quartile, median, third quartile), so the resulting array will look like:

data = [
    {'deviation': 41.48, 'provider': "This", 'measure': "first_quartile"},
    {'deviation': 57.41, 'provider': "This", 'measure': "median"},
    {'deviation': 199.67, 'provider': "This", 'measure': "third_quartile"},
    {'deviation': -1.07, 'provider': "All", 'measure': "first_quartile"}
    {'deviation': 49.02, 'provider': "All", 'measure': "median"},
    {'deviation': 152.31, 'provider': "All", 'measure': "third_quartile"},       
]

I have written a function as an argument to .sort(), and it does return the array sorted by 'provider', but then when I feed it into the same function with measure as an argument (thankfully, first_quartile, median, third_quartile are already alphabetically sorted the way I want them) - the sorting gets broken. How can I go about doing it?

EDIT The functions I have been using:

var compare_prv = function(a,b) {
  if (a.provider < b.provider){
    return 1;
  }
  return 0;
}

var compare_meas = function(a,b) {
  if (a.measure < b.measure){
    return -1;
  }
  return 0;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It sounds like you are doing:

data.sort(function(a, b) {
    //sort by provider
});

data.sort(function(a, b) {
    //sort by measure
});

But what you want to do is:

data.sort(function(a, b) {
    //sort by provider, but if they are equal, sort by measure
});

So something like

data.sort(function(a, b) {
    if (a.provider === b.provider) {
        return a.measure.localeCompare(b.measure);
    }
    return b.provider.localeCompare(a.provider);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...