Sort an array based on another array of integers

前端 未结 7 712
误落风尘
误落风尘 2020-11-27 21:59

Let\'s say I have an array: [0,3,4,2,5,1].

What I want to do is sort an array such as:

[\"one\", \"two\", \"three\", \"four\", \"five\",         


        
7条回答
  •  生来不讨喜
    2020-11-27 22:51

    I was asked this on a phone interview. Then do it without creating another array, supposing the array is very large. I don't know if this is the answer since I wasn't able to do on the call (damn!), but here's what I came up with.

    var my_obj_array = ['a', 'b', 'c', 'd'];
    var my_indicies = [3, 1, 0, 2];
    // desired result ['d', 'b', 'a', 'c']
    
    var temp = {};
    for (var i = 0; i < my_indicies.length; i++) {
        temp[i] = my_obj_array[i];  // preserve
        var j = my_indicies[i];
        if (j in temp) {
            my_obj_array[i] = temp[j];
            delete temp[j];
        } else {
            my_obj_array[i] = my_obj_array[j];
        }
    }
    

    http://jsfiddle.net/innerb/RENjW/

提交回复
热议问题