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

回眸只為那壹抹淺笑 提交于 2020-01-05 14:11:28

问题


I have 5 different arrays that have the same index, eg:

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;

I need to reorder all arrays in the descending order of the need[] array then re-arrange the order of the other arrays based on new index for need[i]. I'm using javascript.

Thank you,

John


回答1:


Sort the need array and save the sort permutation, then apply that permutation to the other arrays. How exactly you do this depends upon the language you're using. For instance, the Matlab sort function can return both the sorted array and the sorting permutation.




回答2:


Don't sort "need". Create an index array, then sort that one according to need. You didn't specify the language though, so you're getting 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);



回答3:


make a copy array that will have same values as in need array (call him sorted array). then look at the original need array - and for every cell find where it is at the sorted array and put the matching values from other arrays to the same cell number that they appear at the sorted array



来源:https://stackoverflow.com/questions/6312236/how-to-sort-an-array-then-take-the-index-and-use-the-index-to-move-all-correspon

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!