如何对数组进行排序,然后获取索引并使用索引移动所有相应的元素

How to sort an array then take the index and use the index to move all corresponding elements?

本文关键字:索引 移动 元素 数组 排序 获取 然后      更新时间:2023-09-26

我有5个不同的数组具有相同的索引,例如:

person[0]="john", address[0]= "Druid Valley", city[0]="Atlanta", amount[0]=2000, need[0]=100; 
person[1]="emily", address[1]="50 decatur", city[1]="Chicago", amount[1]=300; need[1]=50;

我需要按照need[]数组的降序重新排列所有数组,然后根据need[I]的新索引重新排列其他数组的顺序。我使用的是javascript。

谢谢你,

John

need数组进行排序并保存排序排列,然后将该排列应用于其他数组。具体如何做到这一点取决于你使用的语言。例如,Matlab sort函数可以返回排序数组和排序排列。

不要对"need"进行排序。创建一个索引数组,然后根据需要对其进行排序。但是您没有指定语言,所以您得到了JavaScript:

var person = [], need = [];
var person = ["E", "B", "A", "C", "D"];
var need = [111, 444, 555, 333, 222];
var index = [];
var i = person.length;
while (i--) {
  index.push(i);
}
var comparator = function(a, b) {
  var need_a = need[a];
  var need_b = need[b];
  // For robustness - non-numbers get sorted last:
  if (typeof need_a != 'number' || isNaN(need_a)) need_a = -Infinity;
  if (typeof need_b != 'number' || isNaN(need_b)) need_b = -Infinity;
  if (need_a < need_b) return 1;
  if (need_b < need_a) return -1;
  return 0;
}
index.sort(comparator);
// at this point, person[index[0]] is the person with the biggest need.
var sorted_person = [];
var i = index.length;
while (i--) {
  sorted_person[i] = person[index[i]];
}
// at this point, sorted_person[0] is the person with the biggest need.
console.log(sorted_person);

创建一个复制数组,该数组将具有与所需数组相同的值(称为排序数组)。然后查看原始的需求数组-对于每个单元格,找到它在排序数组中的位置,并将其他数组中的匹配值放在排序数组中出现的相同单元格编号中