我正在尝试对两个子索引上的 xy 坐标进行排序,它曾经表示行列 Asc 顺序。我已经通过 Y 对坐标数据进行了排序,但是当我再次通过 X 对该数据进行排序时,我丢失了 Y 顺序,所以知道该怎么做吗?
我做了什么
例子:我的原始坐标xy数据
var cxray = [ [450,13],[455,12],[454,12],[451,12],[452,13],[453,12], [450,12],[453,13],[454,13],[450,13],[452,12],[455,13],];
我的单索引排序函数
this.ray_isort = function(data,i){
data.sort( function( a, b ,sindex=i){if ( parseFloat(a[sindex]) == parseFloat(b[sindex]) ) return 0;return parseFloat(a[sindex]) < parseFloat(b[sindex]) ? -1 : 1;});
return data;
};
fiddle 链接:JSFIDDLE
目前,当我用一个索引对它进行排序时,我得到了输出
0 451,12 1 454,12 2 450,12 3 453,12 4 455,12 5 452,12 6 452,13 7 453,13 8 454,13 9 450,13 10 450,13 11 455,13
我的目标是得到
0 450,12
1 451,12
2 452,12
3 453,12
4 454,12
5 455,12
6 450,13
7 451,13
8 452,13
9 453,13
10 454,13
11 455,13
最佳答案
a[1] - b[1]
将使用每个数组的第二项对数组进行排序。
如果它们相等,结果将为 0
,因此 a[0] - b[0]
部分将被执行,并将使用第一项。
const cxray = [ [450,13],[455,12],[454,12],[451,12],[452,13],[453,12], [450,12],[453,13],[454,13],[450,13],[452,12],[455,13],];
console.log(cxray.sort((a, b) => a[1] - b[1] || a[0] - b[0]));
关于JavaScript,如何通过两个子索引对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45101824/