按两个值排序,优先考虑其中一个值

Doj*_*jie 48 javascript sorting

我如何按值优先排序这些数据count并按year升序排列count值?

//sort this
var data = [
    { count: '12', year: '1956' },
    { count: '1', year: '1971' },
    { count: '33', year: '1989' },
    { count: '33', year: '1988' }
];
//to get this
var data = [
    { count: '1', year: '1971' },
    { count: '12', year: '1956' },
    { count: '33', year: '1988' },
    { count: '33', year: '1989' },
];
Run Code Online (Sandbox Code Playgroud)

cdh*_*wie 72

(见jsfiddle)

data.sort(function (x, y) {
    var n = x.count - y.count;
    if (n !== 0) {
        return n;
    }

    return x.year - y.year;
});
Run Code Online (Sandbox Code Playgroud)

  • 单行`data.sort(function(x,y){return x.count - y.count || x.year - y.year;});` (31认同)
  • @LucaSteeb 您的解决方案像冠军一样有效,挽救了我的一天。 (2认同)

Rob*_*obG 52

一个简单的解决方案是

data.sort(function (a, b) {
  return a.count - b.count || a.year - b.year;
});
Run Code Online (Sandbox Code Playgroud)

这是有效的,因为如果count不同,则排序基于此.如果count相同,则第一个表达式返回0,转换为false,并使用第二个表达式的结果(即排序基于年份).

  • ES 版本: data.sort((a,b)=>(a.count - b.count || a.year - b.year)); (4认同)
  • 很好地使用0作为falsey! (2认同)

Ple*_*and 13

你可以使用JavaScript的.sort()数组方法(试一试):

data.sort(function(a, b) {
    // Sort by count
    var dCount = a.count - b.count;
    if(dCount) return dCount;

    // If there is a tie, sort by year
    var dYear = a.year - b.year;
    return dYear;
});
Run Code Online (Sandbox Code Playgroud)

注意:这会更改原始数组.如果您需要先制作副本,可以这样做:

var dataCopy = data.slice(0);
Run Code Online (Sandbox Code Playgroud)


19W*_*S85 8

基于优秀的@RobG 解决方案,这是一个通用函数,可以使用JS2015棘手的多种不同属性进行排序map + find:

let sortBy = (p, a) => a.sort((i, j) => p.map(v => i[v] - j[v]).find(r => r))

sortBy(['count', 'year'], data)
Run Code Online (Sandbox Code Playgroud)

此外,如果您愿意,还可以使用传统的JS版本(由于在旧版浏览器中找到兼容性,请谨慎使用):

var sortBy = function (properties, targetArray) {
  targetArray.sort(function (i, j) {
    return properties.map(function (prop) {
      return i[prop] - j[prop];
    }).find(function (result) {
      return result;
    });
  });
};
Run Code Online (Sandbox Code Playgroud)


pau*_*aul 6

你必须像这样解决这个问题

var customSort = function(name, type){
     return function(o, p){
         var a, b;
         if(o && p && typeof o === 'object' && typeof p === 'object'){
            a = o[name];
            b = p[name];
           if(a === b){
              return typeof type === 'function' ? type(o, p) : o;
           }

           if(typeof a=== typeof b){
              return a < b ? -1 : 1;
            }
          return typeof a < typeof b ? -1 : 1;
        }
     };
Run Code Online (Sandbox Code Playgroud)

};

例如:data.sort(customSort('year',customSort('count')));