按两个属性和给定顺序对对象的JavaScript数组进行排序

时间:2017-11-13 18:13:28

标签: javascript arrays sorting

我有这个对象的JavaScript数组:

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"}
]

我希望用“提供者”(三个“全部”之前的三个“这个”)和“度量”(第一个四分位数,中位数,第三个四分位数)对它进行排序,因此得到的数组看起来像:

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"},       
]

我已经编写了一个函数作为.sort()的参数,它确实返回按'provider'排序的数组,但是当我将它作为参数提供给同一个函数measure时(谢天谢地,first_quartile,median,third_quartile已经按照我想要的方式按字母顺序排序了 - 排序被打破了。我该怎么做呢?

修改 我一直在使用的功能:

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;
}

2 个答案:

答案 0 :(得分:2)

听起来你在做:

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

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

但你想做的是:

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

类似

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

答案 1 :(得分:0)

您可以使用logical OR ||链接排序条件。

  

对于具有已定义顺序的一组字符串,您可以使用对象来获取所需的顺序。

{
    first_quartile: 1,
    median: 2,
    third_quartile: 3
}
     

这使您可以对某个项目进行排序,如果不是在订单列表中,则ssort以默认值零开始,或者使用像Infinity这样的巨大值来排序。

     

在这种情况下,模式看起来像

(order[a.measure] || 0) - (order[a.measure] || 0)                // to top
(order[a.measure] || Infinify ) - (order[a.measure] || Infinity) // to bottom

&#13;
&#13;
var array = [{ 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" }],
   order = { first_quartile: 1, median: 2, third_quartile: 3 };

array.sort(function (a, b) {
    return b.provider.localeCompare(a.provider) || order[a.measure] - order[b.measure];
});

console.log(array);
&#13;
.as-console-wrapper { max-height: 100% !important; top: 0; }
&#13;
&#13;
&#13;