Reputation: 19
What I'm trying to do is ordering 2 arrays lets say...
let C = [10, 5, 6, 7]
let M = [8, 9, 2, 5]
The first array should stay as it is, but the second needs to be orderer so the output should go like this
[10, 5, 6, 7]
[9, 2, 5, 8]
Basically, i need to order the second array so that the max value matches the max value of the other array.
Please take into account that the first array should stay the same, so i cant reorder both, just the second
To clarify, each array item is a box with that amount of coins and multipliers. One array is coins and the other multipliers.
You can't change the position of the coin boxes, but you can move the multiplier so you can get the max amount of coins. But you can't move the coin boxes from their position.
What i've discover is that in order to get the max amount of coins, you need to multiply the highest possible value, with the highest posible value of the other table. so te correct order would be something like
[1,3,2,4]
[5,7,6,8]
and the values in example are
[5 3 7 1]
[1 4 3 9]
//expected output
[4 3 9 1]
Upvotes: 0
Views: 384
Reputation: 191986
You need to correlate the two arrays by matching the highest number from C
to the highest at M
, and so on until the smallest.
To do so create a new array of indexes (order
), map arr1
, add the index to each item, an then sort the array (I chose descending order).
Now clone arr2
and sort it in the same sort order you've used for C
(descending order) to get the sorted
array.
Now reduce the order
array to another array, take the item with the same index i
from sorted
, and put it in the index idx
taken from the order
array.
const fn = (arr1, arr2) => {
const order = arr1
.map((n, i) => [n, i])
.sort(([n1], [n2]) => n2 - n1)
.map(([, i]) => i)
const sorted = [...arr2].sort((n1, n2) => n2 - n1)
return order.reduce((acc, idx, i) => (acc[idx] = sorted[i], acc), [])
}
console.log(JSON.stringify(fn(
[10, 5, 6, 7],
[8, 9, 2, 5]
))) // [9, 2, 5, 8]
// [2,0,1,3]
console.log(JSON.stringify(fn(
[5, 3, 7, 1],
[1, 4, 3, 9]
))) // [4, 3, 9, 1]
console.log(JSON.stringify(fn(
[5, 4],
[7, 2]
))) // [7, 2]
console.log(JSON.stringify(fn(
[11, 17, 39],
[7, 5, 3]
))) // [3, 5, 7]
Upvotes: 2