简体   繁体   English

对多维数组中的列进行排序

[英]Sorting columns in a multidimensional Array

I want to sort a multidimensional array using the first row, I want that the second and the third row get the same sort order of the first row 我想使用第一行对多维数组进行排序,我希望第二行和第三行获得与第一行相同的排序顺序

Here is an example of array : 这是array的示例:

var arr = 
[
[1,3,5,6,0,2],
[1,2,7,4,0,6],
[1,2,3,4,5,6]
]

the result that I want = 我想要的结果=

[
[0,1,2,3,5,6],
[0,1,6,2,7,4],
[5,1,6,2,3,4]
]

I tried the following function but it doesnt work as I want 我尝试了以下功能,但按我的意愿无法使用

arr = arr.sort(function(a,b) {
  return a[0] > b[0];
});

What's wrong with my function ? 我的功能出了什么问题? Thank you 谢谢

I think I understand what you're looking for: 我想我明白您要寻找的东西:

 a = [ [1,3,5,6,0,2], [1,2,7,4,0,6], [1,2,3,4,5,6] ] transpose = m => m[0].map((_, c) => m.map(r => r[c])); z = transpose(transpose(a).sort((x, y) => x[0] - y[0])) z.map(r => document.write('<pre>'+JSON.stringify(r) + '</pre>')); 

In ES5 在ES5中

transpose = function(m) {
    return m[0].map(function (_, c) {
        return m.map(function (r) {
            return r[c]
        })
    })
};

z = transpose(transpose(a).sort(function (x, y) { return x[0] - y[0] }));

UPD: the transpose trick is kinda "smart", but hardly efficient, if your matrices are big, here's a faster way: UPD:换位技巧有点“聪明”,但是效率不高,如果矩阵很大,这是一种更快的方法:

 a = [ [1,3,5,6,0,2], [1,2,7,4,0,6], [1,2,3,4,5,6] ] t = a[0].map((e, i) => [e, i]).sort((x, y) => x[0] - y[0]); z = a.map(r => t.map(x => r[x[1]])); z.map(r => document.write('<pre>'+JSON.stringify(r) + '</pre>')); 

Basically, sort the first row and remember indexes, then for each row, pick values by an index. 基本上,对第一行进行排序并记住索引,然后对于每一行,按索引选择值。

A bit more verbose than previous answer in ES5 比以前的ES5回答更详细

 var arr = [ [1, 3, 5, 6, 0, 2], [1, 2, 7, 4, 0, 6], [1, 2, 3, 4, 5, 6] ] var sortIndices = arr[0].slice().sort(function(a, b) { return a - b; }).map(function(el) { return arr[0].indexOf(el) }); arr = arr.reduce(function(a, c) { var sorted = sortIndices.map(function(i) { return c[i]; }); a.push(sorted); return a; }, []); document.getElementById('pre').innerHTML = JSON.stringify(arr) 
 <pre id="pre"></pre> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM