英文:
sort array based on sorting of a different array
问题
我有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"]
如何实现这一点?
英文:
I have 2 arrays:
firstArr = ["Pizza", "Pasta", "Chicken Soup", "French Fries"]
secondArr = [8, 6, 6, 9]
now I sort the second Array like this:
secondArr = [9, 8, 6, 6]
I then want the first Array to follow this new order:
firstArr = ["French Fries", "Pizza", "Chicken Soup", "Pasta"]
How can I achieve this?
答案1
得分: 2
以下是代码的翻译部分:
// 合并两个数组,创建一个项目/权重对的数组。
// 对该数组进行排序(首先按权重降序,然后按字母顺序,如果权重相等)。
// 仅返回项目名称。
请注意,这只是代码的翻译部分,不包括问题或其他内容。
英文:
Probably like this:
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)
- Merge the two arrays into one of item / weighting pairs.
 - Sort that (primarily by weighting descending, then alpha where the weightings are equal).
 - Return just the item names.
 
https://trycf.com/gist/e18db87198924030fca231b6b10e4f88/lucee5?theme=monokai
答案2
得分: 0
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; 
      }
   }
}
英文:
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; 
      }
   }
}   
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论