sort outer array based on values in inner array, javascript

后端 未结 3 2004
佛祖请我去吃肉
佛祖请我去吃肉 2020-11-29 10:02

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 confus

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 10:20

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

提交回复
热议问题