javascriptarrayssorting

JavaScript, array.sort() two arrays based on only one of them


I just discovered array.sort() and saw that I can specify how to sort like this: (example taken from http://www.w3schools.com/jsref/jsref_sort.asp)

var points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});

I've been doing my sorting manually just using Bubble Sort because the arrays are small, but I was wondering if array.sort() can be used in place of this:

// Sort rowCategories[i] by rowWidth[i]
swapped = true;
while (swapped) {
    swapped = false;
    for (var i = 0; i < rowCategories.length-1; i++) {
        if (rowWidth[i] < rowWidth[i+1]) {
            var swap = rowCategories[i];
            rowCategories[i] = rowCategories[i+1];
            rowCategories[i+1] = swap;
            swap = rowWidth[i];
            rowWidth[i] = rowWidth[i+1];
            rowWidth[i+1] = swap;
            swapped = true;
        }
    }
}

What would I write for the built in sort to do the equivalent work?


Solution

  • this only requires a little modification. Instead of storing two arrays store one array with an object with the two attributes. Then you can do something like this.

    arr.sort(function(a,b){return a.rowWidth - b.rowWidth});
    

    the object must contain the attributes rowWidth and rowCatagories