排序四维数组 - Javascript

时间:2014-08-03 17:23:40

标签: javascript jquery multidimensional-array

我想使用以下方法对基于1列的四维数组进行排序,

var main_arr = [
    []
];
var hdnFromValues = [11,16,12,17,14,18,15];
var hdnToValues = [12,17,13,18,15,19,16];
var hdnSPIDs = [11,12,13,14,0,0,0];
var hdnFlag = [D,E,E,D,A,A,A];
for (var j = 0; j < hdnFromValues.length; j++) {
    var temp_arr = [];
    var HdnToValue;
    temp_arr.push(hdnFromValues[j]);
    temp_arr.push(hdnToValues[j]);
    temp_arr.push(hdnSPIDs[j]);
    temp_arr.push(hdnFlag[j]);
    main_arr.push(temp_arr);
    temp_arr = null;
}
main_arr.sort(sort_by_col);
hdnFrom = "";
hdnTo = "";
spid = "";
flags = "";
for (var i = 1; i < main_arr.length; i++) {
    hdnFrom = hdnFrom.concat(main_arr[i][0], ",");
    hdnTo = hdnTo.concat(main_arr[i][1], ",");
    spid = spid.concat(main_arr[i][2], ",");
    flags = flags.concat(main_arr[i][3], ",");
}
hdnFrom = hdnFrom.substring(0, hdnFrom.length - 1);
hdnTo = hdnTo.substring(0, hdnTo.length - 1);
spid = spid.substring(0, spid.length - 1);
flags = flags.substring(0, flags.length - 1);
alert(hdnFrom);
alert(hdnTo);
alert(spid);
alert(flags);

function sort_by_col(a, b) {
    return a[0] - b[0];
}

有时,3&amp;第4列没有按照第1列正确排列。

有人会帮助我吗?

JSFilddle

1 个答案:

答案 0 :(得分:0)

更改,

function sort_by_col(a, b) {
    return a[0] - b[0];
}

function sort_by_col(a, b) {
    return a[0] - b[0] || a[1] - b[1];
}