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

How to sort multiple columns data in Multi-Dimensional array?

我正在使用 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 列应用升序(Ascending/descending).

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

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))

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

只需通过获取每列的增量来链接所需的顺序。

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('  ')));

这里你有另一种方法,在排序比较函数上使用更像数学表达式,并且还按照你的预期格式化输出:

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

我也遇到了同样的问题,找到了对多维数组中的多列数据进行排序的好方法。

检查下面的代码

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