我有 2 个数组:
firstArr = ["Pizza", "Pasta", "Chicken Soup", "French Fries"]
secondArr = [8, 6, 6, 9]
现在我像这样对第二个数组进行排序:
secondArr = [9, 8, 6, 6]
然后我希望第一个数组遵循这个新顺序:
firstArr = ["French Fries", "Pizza", "Chicken Soup", "Pasta"]
我怎样才能做到这一点?
int temp = 0;
String temp1 = "";
for(int i=0; i< secondArr.size(); i++) {
for(int j=i+1; j<secondArr.size(); j++) {
if(secondArr[i] < secondArr[j]) {
temp = secondArr[i];
secondArr[i] = secondArr[j];
secondArr[j] = temp;
// To swap the second array if first is swapped on the same index
temp1 = firstArr[i];
firstArr[i] = firstArr[j];
firstArr[j] = temp1;
}
}
}
大概是这样的:
items = ["Pizza", "Pasta", "Chicken Soup", "French Fries"]
weighting = [8, 6, 6, 9]
orderedItems = items
.reduce(
(weightedItems, v, i) => weightedItems.append({item=v, weight=weighting[i]}),
[]
)
.sort((e1, e2) => e2.weight == e1.weight ? compare(e1.item, e2.item) : sgn(e2.weight - e1.weight))
.map((v)=>v.item)
writeDump(orderedItems)