Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

algorithm - 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.

Initial data:

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"
  ]
];

Sort data, based on column with index 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"
  ]
];

Sort data, based on column with index 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"
  ]
];

The big 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...