English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I have two arrays. 1 array is an array of distances from a certain point. I know that if I want to sort this by shortest to farthest distance, that is easily done with an array sort. However, my other array is an array of city names that correspond with the distances in the first array. How could I sort the city array such that it would be identical to the distance array order after a numerical sort? Would it be easier to put them both into one array and some how specify to sort only the distance set? I wouldn't know how to do that. Thanks!

2007-05-20 07:35:23 · 3 answers · asked by johndoi 2 in Computers & Internet Programming & Design

I should have been a little more clear. I was trying to use the array.sort() function rather than writing a sort from scratch

2007-05-20 08:33:41 · update #1

3 answers

You never write a sort from scratch!

sort gets a comparison function... it can get exotic!


a classic comparison function is

function sortByFirstName(a, b) {
var x = a.FirstName.toLowerCase();
var y = b.FirstName.toLowerCase();
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
}

you call it like this:

someArray.sort(sortByFirstName)

the key to writing custom comparison routines is the get the x & y from the other array like

x = otherArray[a]
y = otherArray[b]

2007-05-20 10:20:16 · answer #1 · answered by jake cigar™ is retired 7 · 2 0

Part of the sort process will be to change the place of two distances. Or in the least to move a distance from its current location.
When you do this relocation do exactly the same relocation for the city array.
That is it. It is not all rocket science!

2007-05-20 08:19:56 · answer #2 · answered by AnalProgrammer 7 · 0 0

Sort the first array manually i.e. code your own sorting method, and whenever you make a change to the first array make the same change to the second array.

2016-05-22 01:54:06 · answer #3 · answered by keli 3 · 0 0

fedest.com, questions and answers