我有一个数组,我正在尝试根据另一个数组对该数组重新排序。第二个数组是索引数组(请参见下文)。我正在寻找一个干净的函数来接受两个参数(一个数组和一个索引数组),并返回重新排序的数组。我尝试构建此函数并在下面提供示例,但是它没有返回我期望的结果。任何帮助是极大的赞赏。
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"];
答案 0 :(得分:3)
您可以使用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);
答案 1 :(得分:1)
用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());
答案 2 :(得分:0)
或者如果您不想使用ES6,请使用forEach
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)