1

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?

rrk
  • 15,677
  • 4
  • 29
  • 45
Userx10xC
  • 124
  • 9
  • 1
    So the first and second list have some relationship. Maybe you can try making a list of tuples `[("Pizza", 8),..., ("French Fries", 9)]`, and sort it from the second element of each value (tuple)! [this](https://stackoverflow.com/questions/10695139/sort-a-list-of-tuples-by-2nd-item-integer-value) is in python but I hope you get the idea! – M.K Feb 23 '23 at 12:56
  • 2
    How do you determine the sort order on items with the same weighting value? It's alphabetical in your example, but there's not really enough data to determine whether that's the rule or just a coincidence? – Adam Cameron Feb 23 '23 at 23:05

2 Answers2

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

Adam Cameron
  • 29,677
  • 4
  • 37
  • 78
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; 
      }
   }
}