如何对数组进行排序,然后使用索引并使用索引来移动所有对应的元素? [英] How to sort an array then take the index and use the index to move all corresponding elements?

查看:105
本文介绍了如何对数组进行排序,然后使用索引并使用索引来移动所有对应的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

我需要按照Need []数组的降序对所有数组进行重新排序,然后根据需要的新索引重新排列其他数组的顺序.我正在使用javascript.

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.

谢谢

约翰

推荐答案

不要对需要"进行排序.创建一个索引数组,然后根据需要对该索引进行排序.您虽然没有指定语言,但是却获得了JavaScript:

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

这篇关于如何对数组进行排序,然后使用索引并使用索引来移动所有对应的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆