根据javaScript中给定的索引对数组重新排序

时间:2018-08-29 12:25:21

标签: javascript arrays

我面临根据javaScript中给定索引更改数组的索引值的问题。我在StackOverflow上搜索并找到了一些解决方案,但那些不适用于我的解决方案不适用于javaScript。下面提到了输入数组和索引。

   Input:  arr[]   = [101, 102, 103];
   index[] = [1, 0, 2];
   Output: arr[]   = [102, 101, 103]
   index[] = [0,  1,  2] 

已建立的答案是 reorder array according to given index

php - sort an array according to second given array

Rearrange an array according to key

Sorting an Array according to the order of another Array

任何提示/解决方案都受到高度赞赏。

3 个答案:

答案 0 :(得分:3)

什么对您不起作用?

const arr = [101, 102, 103];
const index = [1, 0, 2];

const output = index.map(i => arr[i]);
console.log(output);

答案 1 :(得分:1)

希望这会有所帮助!

下面我们使用.map,因为它返回一个新的数组并遍历indexes,因为我们要使用unorderedindexes进行排序。

我们使用index中的当前indexesunordered中选择并返回值。

// ES5
var unordered = [101, 102, 103];
var indexes = [1, 0, 2];

var ordered = indexes.map(function(index) {
  return (unordered[index]);
});

console.log(ordered);

// ES6
const unordered = [101, 102, 103];
const indexes = [1, 0, 2];

console.log(
  indexes.map(index => (unordered[index]))
);

如果要取回indexes阵列的ordered,可以使用下面的方法。

var ordered = indexes.reduce(function(accumulate, index, j) {
  accumulate['values'].push(unordered[index]);
  accumulate['indexes'].push(j);

  return accumulate;
}, { 'values': [], 'indexes': []});

console.log(ordered);

答案 2 :(得分:1)

您可以循环并添加到新数组中

var arr    = [101, 102, 103];
var index = [1, 0, 2];
var newArr =[];

for(var i=0;i<index.length ;i++){
   newArr[i]=arr[index[i]]
 }
  console.log(newArr);