根据内部数组中的值对外部数组进行排序,javascript [英] sort outer array based on values in inner array, javascript

查看:25
本文介绍了根据内部数组中的值对外部数组进行排序,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);

对象看起来像这样;

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);

对象看起来像这样;

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

推荐答案

Array#sort(参见 规范,或 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;
});

(您显然可以稍微压缩该代码;为了清楚起见,我将其保留得很详细.)

(You can obviously compress that code a bit; I've kept it verbose for clarity.)

这篇关于根据内部数组中的值对外部数组进行排序,javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆