简体   繁体   English

根据特定顺序对两个 arrays 进行排序

[英]Sorting two arrays according specific order

What I'm trying to do is ordering 2 arrays lets say...我想做的是订购 2 arrays 让我们说......

 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第一个数组应该保持原样,但第二个数组需要排序,所以 output 应该像这样 go

 [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.您无法更改硬币盒的 position,但您可以移动乘数以获得最大数量的硬币。 But you can't move the coin boxes from their position.但是你不能从他们的 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]

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.您需要将两个 arrays 相关联,方法是将C中的最高数字与M处的最高数字相匹配,依此类推直到最小。

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).为此,创建一个新的索引数组( order ),map arr1 ,将索引添加到每个项目,然后对数组进行排序(我选择降序)。

Now clone arr2 and sort it in the same sort order you've used for C (descending order) to get the sorted array.现在克隆arr2并按照您用于C的相同排序顺序(降序)对其进行排序以获得sorted数组。

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.现在将order数组缩减为另一个数组,从sorted中取出具有相同索引i的项目,并将其放入从order数组中取出的索引idx中。

 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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM