Sort two arrays the same way
You can sort the existing arrays, or reorganize the data.
Method 1:
To use the existing arrays, you can combine, sort, and separate them:
(Assuming equal length arrays)
var names = ["Bob","Tom","Larry"];
var ages = ["10", "20", "30"];
//1) combine the arrays:
var list = [];
for (var j = 0; j < names.length; j++)
list.push({'name': names[j], 'age': ages[j]});
//2) sort:
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
//Sort could be modified to, for example, sort on the age
// if the name is the same.
});
//3) separate them back out:
for (var k = 0; k < list.length; k++) {
names[k] = list[k].name;
ages[k] = list[k].age;
}
This has the advantage of not relying on string parsing techniques, and could be used on any number of arrays that need to be sorted together.
Method 2: Or you can reorganize the data a bit, and just sort a collection of objects:
var list = [
{name: "Bob", age: 10},
{name: "Tom", age: 20},
{name: "Larry", age: 30}
];
list.sort(function(a, b) {
return ((a.name < b.name) ? -1 : ((a.name == b.name) ? 0 : 1));
});
for (var i = 0; i<list.length; i++) {
alert(list[i].name + ", " + list[i].age);
}
For the comparisons,-1 means lower index, 0 means equal, and 1 means higher index. And it is worth noting that sort()
actually changes the underlying array.
Also worth noting, method 2 is more efficient as you do not have to loop through the entire list twice in addition to the sort.
http://jsfiddle.net/ghBn7/38/
Sort multiple arrays based on one array
You could get an array of sorted indices and map sorted arrays.
const
arrays = [[2, 3, 1], ["deux", "trois", "un"], ["zwei", "drei", "eins"]],
sorted = arrays.map(
(indices => a => indices.map(i => a[i]))
([...arrays[0].keys()].sort((a, b) => arrays[0][a] - arrays[0][b]))
);
console.log(sorted);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sorting multiple arrays based on one
Use a hash as your intuition was leading you to:
var scores = [2, 5, 3, 1, 4];
var countries = ["Canada", "Macau", "Sweden", "France", "China"];
var score = {};
for( var i=0,n=scores.length; i<n; i++){
score[scores[i]] = countries[i];
}
for( var key in keys=Object.keys(score).sort() ){
var prop = keys[key];
console.log(prop, score[prop]);
}
How to sort multiple arrays based on one and print them out
Using the techniques used in this answer, you can create an array of indices, and sort the index array based on the criteria you're interested in. Then when referencing the data in a sorted manner, you use the index array.
#include <vector>
//...
std::vector<int> index_array;
int main()
{
for (int i = 0; i < number_of_items; ++i)
index_array.push_back(i);
//...
SelectionSort(city, size)
}
void SelectionSort(string city[], int size)
{
int i;
int j;
int indexSmallest;
string temp;
for (i = 0; i < size; ++i)
{
indexSmallest = i;
for (j = i + 1; j < size; ++j)
{
if (city[index_array[j]] < city[index_array[indexSmallest]])
{
indexSmallest = j;
}
}
temp = index_array[i];
index_array[i] = index_array[indexSmallest];
index_array[indexSmallest] = temp;
}
}
Then when accessing the arrays, use the array of indices:
for (int i = 0; i < size; ++i)
std::cout << city[index_array[i]] << "\n" << names[index_array[i]] << "\n\n";
How can I sort many arrays according to one array?
Here's a trick I've used.
my @permutation = sort { $numbers[$a] <=> $numbers[$b] } (0..$#numbers);
@colors = @colors[@permutation];
@numbers = @numbers[@permutation];
@hats = @hats[@permutation];
# No change to %hash needed, since it has references to above arrays.
How can I sort multiple arrays based on the sorted order of another array
You can do this by first sorting an array of the keying array’s indices by the values they index, then generating new arrays based on those sorted indices, using PermutationGenerator
:
let myArr = ["b", "a", "c"]
let myArr2 = ["letter b", "letter a", "letter c"]
let myArr3 = ["b is the second letter", "a is the first letter", "c is the third letter"]
func sortByKeyArray(keyArray: [String], valuesArrays: [[String]]) -> [[String]] {
precondition(reduce(valuesArrays, true) { $0.0 && ($0.1.count == keyArray.count)},
"Arrays all need to be the same length")
let permutation = sorted(indices(keyArray)) {
keyArray[$0] < keyArray[$1]
}
return valuesArrays.map {
Array(PermutationGenerator(elements: $0, indices: permutation))
}
}
sortByKeyArray(myArr, [myArr2, myArr3])
// returns [["letter a", "letter b", "letter c"], ["a is the first letter", "b is the second letter", "c is the third letter"]]
If you want to make this generic on any kind of collection (but still returning an array, in the same style as the std lib collection algos):
func sortByKeyingCollection<C: CollectionType, D: SequenceType
where D.Generator.Element == C,
C.Index: RandomAccessIndexType,
C.Generator.Element: Comparable>
(key: C, values: D) -> [[C.Generator.Element]] {
let permutation = sorted(indices(key)) {
key[$0] < key[$1]
}
return map(values) {
Array(PermutationGenerator(elements: $0, indices: permutation))
}
}
And a version that takes a custom comparator:
func sortByKeyingCollection<C: CollectionType, D: SequenceType where D.Generator.Element == C, C.Index: RandomAccessIndexType>(key: C, values: D, isOrderedBefore: (C.Generator.Element,C.Generator.Element)->Bool) -> [[C.Generator.Element]] {
let permutation = sorted(indices(key)) {
isOrderedBefore(key[$0],key[$1])
}
return map(values) {
Array(PermutationGenerator(elements: $0, indices: permutation))
}
}
sortByKeyingCollection(myArr, [myArr2, myArr3], >)
sortByKeyingCollection(myArr, [myArr2, myArr3], lexicographicalCompare)
sortByKeyingCollection(myArr, [myArr2, myArr3]) { dropFirst($0) < dropFirst($1) }
Sorting multiple arrays based on another arrays sorted order
[sorted, indices] = sort(c)
% get your output with
a(indices)
b(indices)
Related Topics
How to Sort an Array of Posts by Their Elements
Where to Place App Delegate Code in App.Swift File
Value of Type 'Authdataresult' Has No Member 'Uid'
Don't Delete Some Rows from Uitableview
How to Get Exactly the Same Point on Different Screen Sizes
Get Element from Array of Dictionaries According to Key
My Button Is Centered for iPhone 6 and 6 Plus, But Not for iPhone 5
Store Data in Custom Class Array in Core Data
Code Only Retrieving One Value from Data in Firebase
Alamofireimage How to Clean Memory and Cache
Hiding Dividers in Nssplitview
(Cross-)Compiling Swift for Raspberry Pi
Nsmanagedobject Subclasses Duplicate Declaration