根据不同数组的排序对数组进行排序

huangapple go评论51阅读模式
英文:

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 = &quot;&quot;;
for(int i=0; i&lt; secondArr.size(); i++) {
   for(int j=i+1; j&lt;secondArr.size(); j++) {
      if(secondArr[i] &lt; 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; 
      }
   }
}   

huangapple
  • 本文由 发表于 2023年2月23日 20:43:19
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545006.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定