How to rearrange an array by indices array?

前端 未结 9 1950
故里飘歌
故里飘歌 2021-02-01 19:12

Given an array arr and an array of indices ind, I\'d like to rearrange arr in-place to satisfy the given indices. For exa

9条回答
  •  佛祖请我去吃肉
    2021-02-01 19:30

    I'm not sure on the time, but the map function does appear to do what was requested. It's an option, but since I don't know the inner workings of .map then I can't say for sure this is what you're looking for.

    var arr = ["A", "B", "C", "D", "E", "F"];
    var ind = [4, 0, 5, 2, 1, 3];
    
    arr = ind.map(function(value)
    { return arr[value]; });
    

    Another solution that doesn't use the map function could look something like this:

    var arr = ["A", "B", "C", "D", "E", "F"];
    var ind = [4, 0, 5, 2, 1, 3];
    
    var temp = [];
    
    for (var i = 0, ind_length = ind.length; i < ind_length; i++) 
    { 
        var set_index = ind[i];
        temp.push(arr[set_index]); 
        delete arr[set_index]; 
    }
    
    arr = temp;
    

    This makes good use of space by using the delete option which also keeps the indexes from shifting. Since it's only doing one loop I imagine the execution is rather fast. Since the commands are very basic and simple this should be a viable solution. It's not quite what was asked which was a swap with no extra space used, but it comes pretty close. I'm new to answering questions like this one so please... constructive criticism.

提交回复
热议问题