排序外阵列的基础上的内部数组值,JavaScript的 [英] sort outer array based on values in inner array, javascript
问题描述
我有阵列它,在这里我想基于在内部特定的列值外数组排序的数组。
I have an array with arrays in it, where I want to sort the outer arrays based on values in a specific column in the inner.
我敢打赌,听起来多了有点混乱,所以我就直接跳到一个例子。
I bet that sounded more than a bit confusing, so I'll skip straight to an example.
初始数据:
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"
]
];
排序数据的基础上,列有索引1
data.sortFuncOfSomeKind(1);
在对象则是这样的;
where the object then would look like this;
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"
]
];
排序数据的基础上,列有索引2
data.sortFuncOfSomeKind(2);
在对象则是这样的;
where the object then would look like this;
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"
]
];
的大Q
有没有一个现有的解决方案,这一点,你知道的,或者我会写一个自己?如果是这样,这将是最容易排序算法使用?快速排序?
Is there an existing solution to this that you know of, or would I have to write one myself? If so, which would be the easiest sort algorithm to use? QuickSort?
_L
推荐答案
阵列#排序
(见的规范或的 MDC )接受一个可选功能参数将被用来比较两个条目排序。该函数将返回-1,如果第一个参数是小于第二,0如果他们是平等的,或者1如果第一个是大于第二个。所以:
Array#sort
(see section 15.4.4.11 of the spec, or MDC) accepts an optional function parameter which will be used to compare two entries for sorting purposes. The function should return -1 if the first argument is "less than" the second, 0 if they're equal, or 1 if the first is "greater than" the second. So:
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;
});
(可以很明显的COM preSS是codeA位。我已经把它详细的清晰度)
(You can obviously compress that code a bit; I've kept it verbose for clarity.)
这篇关于排序外阵列的基础上的内部数组值,JavaScript的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!