Sort two arrays the same way

前端 未结 12 2261
爱一瞬间的悲伤
爱一瞬间的悲伤 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:32

    It is very similar to jwatts1980's answer (Update 2). Consider reading Sorting with map.

    name.map(function (v, i) {
        return {
            value1  : v,
            value2  : age[i]
        };
    }).sort(function (a, b) {
        return ((a.value1 < b.value1) ? -1 : ((a.value1 == b.value1) ? 0 : 1));
    }).forEach(function (v, i) {
        name[i] = v.value1;
        age[i] = v.value2;
    });
    

提交回复
热议问题