如何对多维数组中的多列数据进行排序?

时间:2019-01-24 13:22:54

标签: javascript arrays columnsorting

我正在使用Javascript代码,其中有如下所示的数组:

数组:

[
    ["2015-08-09", 1.2, 1.20, 2.1],
    ["2015-08-10", 1.2, 1.21, 2.11],
    ["2015-08-11", 1.2, 0.99, 2.20],
    ["2015-10-29", 1.2, 1.12, 2.22],
    ["2015-09-10", 1.21, 1.19, 2.00]
]

我所需的结果是:

[
    ["2015-08-09", 1.20, 1.20, 2.10],
    ["2015-08-10", 1.20, 1.21, 2.11],
    ["2015-08-11", 1.20, 0.99, 2.20],
    ["2015-10-29", 1.20, 1.12, 2.22],
    ["2015-09-10", 1.21, 1.19, 2.00]
]

由于数组是3维的,所以我想对column 12进行排序,因此首先对列1应用升序,然后对列2应用降序(升序/降序)

谢谢。

4 个答案:

答案 0 :(得分:3)

我也面临同样的问题,并且找到了一种对多维数组中的多列数据进行排序的好方法。

检查以下代码

(function() {
      function deepsort(){
    var i, order= arguments, L= order.length, tem;
    return a.sort(function(a, b){
        i= 0;
      
        while(i < L){
          
            tem= order[i++];
          var res = tem.split("_");
            var ao= a[res[0]] || 0, bo= b[res[0]] || 0;
            if(ao== bo) continue;
           
          if(res[1] == "ASC"){
            return ao > bo? 1: -1;
          }
          if(res[1] == "DESC"){
             return ao < bo? 1: -1;
          }
        }
        return 0;
    });
}

var a= [
    ["2015-08-09", 1.2, 1.20, 2.1],
    ["2015-08-10", 1.2, 1.21, 2.11],
    ["2015-08-11", 1.2, 0.99, 2.20],
    ["2015-10-29", 1.2, 1.12, 2.22],
    ["2015-09-10", 1.21, 1.19, 2.00]
];
document.write(deepsort(1+"_ASC",2+"_ASC"));
// for better result view check console log
console.log(deepsort(1+"_ASC",2+"_ASC"))
//console.log(a.deepsort(1))
    
    })();

答案 1 :(得分:2)

这里,您还有另一种在排序比较函数上使用更类似数学表达式的方法,并且可以按预期设置输出的格式:

const input = [
    ["2015-08-09", 1.2, 1.20, 2.1],
    ["2015-08-10", 1.2, 1.21, 2.11],
    ["2015-08-11", 1.2, 0.99, 2.20],
    ["2015-10-29", 1.2, 1.12, 2.22],
    ["2015-09-10", 1.21, 1.19, 2.00]
];

// First, we use map() to clone the array so we don't change
// the original, and also to format the numbers as you expect.

let res = input.map(
  ([a, b, c, d]) => [a, b.toFixed(2), c.toFixed(2), d.toFixed(2)]
);

// Now we sort the new array using a more-like mathematical expression.

res.sort((x, y) =>
{
    let n = x[1] - y[1], m = x[2] - y[2];
    return n +  m * (n === 0);
});

console.log(res);

答案 2 :(得分:1)

只需通过获取每列的增量来链接所需的订单即可。

var array = [["2015-08-09", 1.2, 1.2], ["2015-08-10", 1.2, 1.21], ["2015-08-11", 1.2, 0.99], ["2015-10-29", 1.2, 1.12], ["2015-09-10", 1.21, 1.19]];

array.sort((a, b) => a[1] - b[1] || a[2] - b[2]);

console.log(array.map(a => a.join('  ')));

答案 3 :(得分:-1)

实际上,您的数组是二维的。您可以使用与一维数组相同的方式对其进行排序:

const data = [
  [ "2015-08-09", 1.2, 1.2], 
  [ "2015-08-10", 1.2, 1.21], 
  [ "2015-08-11", 1.2, 0.99],
  [ "2015-10-29",  1.2, 1.12] , 
  [ "2015-09-10",  1.21, 1.19]   
]

function sort(a, b) {
  const col1 = new Date(a[0]) - new Date(b[0]);
  if (col1 === 0) {
    return a[1] - b[1];
  }
  return col1;
}

console.log(data.sort(sort))

在上面的示例中,我们首先按照内部数组中的第一个字段进行排序。如果值相等-那么我们比较内部数组的第二个字段。