代码之家  ›  专栏  ›  技术社区  ›  Developing

使用javascript按索引重新排序数组[重复]

  •  -1
  • Developing  · 技术社区  · 7 年前

    这个问题已经有了答案:

    我有一个数组,我正在尝试根据另一个数组重新排序这个数组。第二个数组是一个索引数组(见下文)。我希望构建一个干净的函数来获取两个参数(一个数组和一个索引数组),并返回重新排序的数组。我试过构建这个函数并在下面举一个例子,但是它并没有返回我所期望的。非常感谢您的帮助。

    var before = ["T", "T", "A", "T", "T", "T", "T", "T", "A", "T", "T","T", "W", "W", "W", "W", "T", "T", "T", "T", "T", "W", "T"];
    var indexes = [8, 2, 11, 22, 0, 4, 5, 18, 6, 17, 16, 19, 7, 3, 20, 1, 10, 9, 14, 13, 21, 12, 15];
    
    // Attempt
    function reorderArray(arrayToOrder ,order){
        // Get a copy of the array we want to change
        var temp = arrayToOrder
        // loop through the indexes
        // use the indexes to place the items in the right place from the copy into the original
        for(let i = 0; i < arrayToOrder.length; i++) {
            console.log("arr: ", arrayToOrder[order[i]] );
            console.log("temp: ", temp[i] );
            arrayToOrder[order[i]] = temp[i];
        }
        return arrayToOrder;
    }
    // run function
    reorderArray( before, indexes );
    
    // function should return this array
    var after = ["A", "A", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "T", "W", "W", "W", "W", "W"];
    
    3 回复  |  直到 7 年前
        1
  •  3
  •   Zohaib Ijaz    7 年前

    你可以用 Array.prototype.map

    var before = ["T", "T", "A", "T", "T", "T", "T", "T", "A", "T", "T","T", "W", "W", "W", "W", "T", "T", "T", "T", "T", "W", "T"];
    var indexes = [8, 2, 11, 22, 0, 4, 5, 18, 6, 17, 16, 19, 7, 3, 20, 1, 10, 9, 14, 13, 21, 12, 15];
    
    var output = indexes.map(i => before[i]);
    
    console.log(output);
        2
  •  1
  •   Ori Drori    7 年前

    迭代 indexes 具有 Array.map() ,并返回 before 数组:

    const before = ["T", "T", "A", "T", "T", "T", "T", "T", "A", "T", "T","T", "W", "W", "W", "W", "T", "T", "T", "T", "T", "W", "T"];
    const indexes = [8, 2, 11, 22, 0, 4, 5, 18, 6, 17, 16, 19, 7, 3, 20, 1, 10, 9, 14, 13, 21, 12, 15];
    
    const reorderByIndexes = (arr, order) => order.map((index) => arr[index]);
      
    const after = reorderByIndexes(before, indexes);
    
    console.log(after.join());
        3
  •  0
  •   Mark Schultheiss    7 年前

    如果你不想使用ES6,就用前臂。

    var before = ["T", "T", "A", "T", "T", "T", "T", "T", "A", "T", "T", "T", "W", "W", "W", "W", "T", "T", "T", "T", "T", "W", "T"];
    var indexes = [8, 2, 11, 22, 0, 4, 5, 18, 6, 17, 16, 19, 7, 3, 20, 1, 10, 9, 14, 13, 21, 12, 15];
    var after = [];
    indexes.forEach(function(value, index) {
      after[index] = before[value]
    })
    
    console.log(after)