如何在javascipt中对数据数组进行分组和排序?

时间:2019-10-23 21:31:18

标签: javascript json sorting

以下是json数据,其中quarter的顺序为descending。我想始终保持quarter的降序。如何按valuedateCreated排序?


 data = [
    { id: 0, quarter: 4, category: 'Apple',  value: 5, dateCreated: "12:00:00 10/15/2019" },
    { id: 1, quarter: 4, category: 'Orange', value: 2, dateCreated: "12:00:00 10/10/2019" },
    { id: 3, quarter: 4, category: 'Pear',   value: 9, dateCreated: "12:00:00 01/21/2019" },

    { id: 4, quarter: 3, category: 'Apple',  value: 4, dateCreated: "12:00:00 01/08/2019" },
    { id: 5, quarter: 3, category: 'Orange', value: 9, dateCreated: "12:00:00 01/09/2019" },
    { id: 6, quarter: 3, category: 'Pear',   value: 2, dateCreated: "12:00:00 01/07/2016" },

    { id: 7, quarter: 2, category: 'Apple',  value: 6, dateCreated: "12:00:00 01/05/2019" },
    { id: 8, quarter: 2, category: 'Orange', value: 5, dateCreated: "12:00:00 01/04/2019" },
    { id: 9, quarter: 2, category: 'Pear',   value: 7, dateCreated: "12:00:00 01/06/2019" },
];

2 个答案:

答案 0 :(得分:1)

尝试按value进行排序,如果需要,您也可以简单地用dateCreated代替

cmp = function(x, y){
    return x > y ? 1 : x < y ? -1 : 0; 
};

// Sort by quarter then by value
data.sort(function(a, b){
    // Note the minus before cmp, for descending order
    return cmp([-cmp(a.quarter, b.quarter), -cmp(a.value, b.value)], [-cmp(b.quarter, a.quarter), -cmp(b.value, a.value)]);
});

答案 1 :(得分:1)

您可以创建自己的可重复使用的排序功能:

// Minified for less cluttering, but the same Array as you have
var data=[{id:0,quarter:4,category:"Apple",value:5,dateCreated:"12:00:00 10/15/2019"},{id:1,quarter:4,category:"Orange",value:2,dateCreated:"12:00:00 10/10/2019"},{id:3,quarter:4,category:"Pear",value:9,dateCreated:"12:00:00 01/21/2019"},{id:4,quarter:3,category:"Apple",value:4,dateCreated:"12:00:00 01/08/2019"},{id:5,quarter:3,category:"Orange",value:9,dateCreated:"12:00:00 01/09/2019"},{id:6,quarter:3,category:"Pear",value:2,dateCreated:"12:00:00 01/07/2016"},{id:7,quarter:2,category:"Apple",value:6,dateCreated:"12:00:00 01/05/2019"},{id:8,quarter:2,category:"Orange",value:5,dateCreated:"12:00:00 01/04/2019"},{id:9,quarter:2,category:"Pear",value:7,dateCreated:"12:00:00 01/06/2019"}];

function customSort(array, props, direction) {
  array.sort(function (a, b) {
    if (direction === 'asc') {
      // Swap the two items
      var tmp = b;
      b = a;
      a = tmp;
    }
    for (var i = 0; i < props.length; i++) {
      if (a[props[i]] < b[props[i]]) return 1;
      if (a[props[i]] > b[props[i]]) return -1;
    }
    return 0;
  });
}

customSort(data, ['quarter', 'value'], 'desc');
console.log(data);

customSort(data, ['quarter', 'dateCreated'], 'desc');
console.log(data);

customSort(data, ['quarter'], 'asc');
console.log(data);