Sort two arrays the same way

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

    You are trying to sort 2 independet arrays by only calling sort() on one of them.

    One way of achieving this would be writing your own sorting methd which would take care of this, meaning when it swaps 2 elements in-place in the "original" array, it should swap 2 elements in-place in the "attribute" array.

    Here is a pseudocode on how you might try it.

    function mySort(originals, attributes) {
        // Start of your sorting code here
            swap(originals, i, j);
            swap(attributes, i, j);
        // Rest of your sorting code here
    }
    

提交回复
热议问题