基于内部数组javascript中的值对外部数组进行排序

ptr*_*trn 7 javascript sorting algorithm

我有一个包含数组的数组,我想根据内部特定列中的值对外部数组进行排序.

我打赌这听起来有点混乱,所以我会直接跳到一个例子.

初步数据:

var data = [
  [
    "row_1-col1",
    "2-row_1-col2",
    "c-row_1-coln"
  ],
  [
    "row_2-col1",
    "1-row_2-col2",
    "b-row_2-coln"
  ],
  [
    "row_m-col1",
    "3-row_m-col2",
    "a-row_m-coln"
  ]
];
Run Code Online (Sandbox Code Playgroud)

根据索引为1的列对数据进行排序

data.sortFuncOfSomeKind(1);
Run Code Online (Sandbox Code Playgroud)

然后对象看起来像这样;

var data = [
  [
    "row_2-col1",
    "1-row_2-col2",
    "b-row_2-coln"
  ],
  [
    "row_1-col1",
    "2-row_1-col2",
    "c-row_1-coln"
  ],
  [
    "row_m-col1",
    "3-row_m-col2",
    "a-row_m-coln"
  ]
];
Run Code Online (Sandbox Code Playgroud)

根据索引为2的列对数据进行排序

data.sortFuncOfSomeKind(2);
Run Code Online (Sandbox Code Playgroud)

然后对象看起来像这样;

var data = [
  [
    "row_m-col1",
    "3-row_m-col2",
    "a-row_m-coln"
  ],
  [
    "row_2-col1",
    "1-row_2-col2",
    "b-row_2-coln"
  ],
  [
    "row_1-col1",
    "2-row_1-col2",
    "c-row_1-coln"
  ]
];
Run Code Online (Sandbox Code Playgroud)

大Q.

你知道吗,或者我必须自己写一个解决方案吗?如果是这样,哪个是最容易使用的排序算法?快速排序?

_L

T.J*_*der 9

Array#sort(参见规范的第15.4.4.11节或MDC)接受一个可选的函数参数,该参数将用于比较两个条目以进行排序.如果第一个参数是"小于"第二个参数,则函数应该返回-1,如果它们相等则返回0,如果第一个参数是"大于"第二个参数,则返回1.所以:

outerArray.sort(function(a, b) {
    var valueA, valueB;

    valueA = a[1]; // Where 1 is your index, from your example
    valueB = b[1];
    if (valueA < valueB) {
        return -1;
    }
    else if (valueA > valueB) {
        return 1;
    }
    return 0;
});
Run Code Online (Sandbox Code Playgroud)

(你显然可以稍微压缩一下这些代码;为了清楚起见,我保持冗长.)


Sea*_*sey 7

这是一个不需要单独变量来包含索引的解决方案

var arr = [.....]
arr.sort((function(index){
    return function(a, b){
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
    };
})(2)); // 2 is the index
Run Code Online (Sandbox Code Playgroud)

这对索引 2 进行排序