How to rearrange an array by indices array?

前端 未结 9 1928
故里飘歌
故里飘歌 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:48

    Try this:

    var result = new Array(5);
    for (int i = 0; i < result.length; i++) {
        result[i] = arr[ind[i]];
    }
    console.log(arr);
    
    0 讨论(0)
  • 2021-02-01 19:54

    I am using ind as indexes in it's own order

    var arr = ["A", "B", "C", "D", "E", "F"];
    var ind = [4, 0, 5, 2, 1, 3];
    var obj = {}
    for(var i=0;i<arr.length;i++)
        obj[ind[i]]=arr[i];
    console.log(obj);
    

    Working Fiddle

    0 讨论(0)
  • 2021-02-01 19:56
    var arr = ["A", "B", "C", "D", "E", "F"];
    var ind = [4, 0, 5, 2, 1, 3];
    
    function rearrange(arr, ind){
      var map = [];
      for (var i = 0; i < arr.length; i++)   map[ind[i]] = arr[i];
      for (var i = 0; i < arr.length; i++)   arr[i] = map[i];
    }
    
    rearrange(arr, ind);
    
    console.log(arr);
    

    That works but, because I'm not a smart developper, I assume it's probably not the fastest algorithm.

    0 讨论(0)
提交回复
热议问题