Sort two arrays the same way

前端 未结 12 2246
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 15:48

For example, if I have these arrays:

var name = [\"Bob\",\"Tom\",\"Larry\"];
var age =  [\"10\", \"20\", \"30\"];

And I use name.sort

12条回答
  •  借酒劲吻你
    2020-11-27 16:47

    You can sort the existing arrays, or reorganize the data.

    Method 1: To use the existing arrays, you can combine, sort, and separate them: (Assuming equal length arrays)

    var names = ["Bob","Tom","Larry"];
    var ages =  ["10", "20", "30"];
    
    //1) combine the arrays:
    var list = [];
    for (var j = 0; j < names.length; j++) 
        list.push({'name': names[j], 'age': ages[j]});
    
    //2) sort:
    list.sort(function(a, b) {
        return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
        //Sort could be modified to, for example, sort on the age 
        // if the name is the same.
    });
    
    //3) separate them back out:
    for (var k = 0; k < list.length; k++) {
        names[k] = list[k].name;
        ages[k] = list[k].age;
    }
    

    This has the advantage of not relying on string parsing techniques, and could be used on any number of arrays that need to be sorted together.

    Method 2: Or you can reorganize the data a bit, and just sort a collection of objects:

    var list = [
        {name: "Bob", age: 10}, 
        {name: "Tom", age: 20},
        {name: "Larry", age: 30}
        ];
    
    list.sort(function(a, b) {
        return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
    });
    
    for (var i = 0; i

    For the comparisons,-1 means lower index, 0 means equal, and 1 means higher index. And it is worth noting that sort() actually changes the underlying array.

    Also worth noting, method 2 is more efficient as you do not have to loop through the entire list twice in addition to the sort.

    http://jsfiddle.net/ghBn7/38/

提交回复
热议问题