John
John

Reputation: 41

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

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

Upvotes: 1

Views: 807

Answers (3)

Amadan
Amadan

Reputation: 198314

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);

Upvotes: 1

Witterquick
Witterquick

Reputation: 6150

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

Upvotes: 0

PengOne
PengOne

Reputation: 48398

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.

Upvotes: 1

Related Questions