简体   繁体   中英

How to sort 2 separate arrays by Number values?

I have 2 array variables in javascript as below

var distance = [10, 5, 2, 11, 12];
var places = ['A', 'B', 'C', 'D', 'E'];

What I want to do is, I want to sort the distance array so that the numbers should come up in ascending order, and based that, the places should also come up. So the output arrays should be like below

var distance = [2, 5, 10, 11, 12];
var places = ['C', 'B', 'A', 'D', 'E'];

I tried to sort distance array using below code which worked well but then I do not know what logic should I use to apply the changed indexes to places array.

distance.sort(function(a,b){return a - b});

Try this. JSFIDDLE

var distance = [10, 5, 2, 11, 12];
var places = ['A', 'B', 'C', 'D', 'E'];
var action = []; 
distance.sort(function(a,b){
    var c= a-b; 
    action.push(c); 
    return c; 
});
var i=0;
places.sort(function(){
      return action[i++];
});

console.log(distance);
console.log(places);

OR You can try this

var distance = [10, 5, 2, 11, 12];
var places = ['A', 'B', 'C', 'D', 'E'];

var newArray = [];
distance.forEach(function(v, index){
    newArray.push({key: v, value: places[index]})
});

newArray.sort(function(a, b){
  return a.key - b.key;
});
distance = [];
places = [];
newArray.forEach(function(v){
    distance.push(v.key);
    places.push(v.value);
});

console.log(distance);
console.log(places);

What you probably want to do is to combine the place and distance into an object so you can have a single array of objects. You can then sort that single array and all place and distance values will stay associated in the sorted array.

var data = [
    {distance: 10, place: 'A'},
    {distance: 5, place: 'B'},
    {distance: 2, place: 'C'},
    {distance: 11, place: 'D'},
    {distance: 12, place: 'E'}
];

data.sort(function(a, b) {
    return a.distance - b.distance;
});

// result would be:

[
    {distance: 2, place: 'C'},
    {distance: 5, place: 'B'},
    {distance: 10, place: 'A'},
    {distance: 11, place: 'D'},
    {distance: 12, place: 'E'}
];

FYI, this type of storage structure is also useful for adding or removing an item from the list because you just add or remove a single object from the array rather than doing double maintenance on two arrays. Imagine if you had several more properties of the place besides just distance. This array of objects structure is much more scalable and foolproof to maintain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM