简体   繁体   English

如何对 JS 的 arrays 使用自定义排序进行排序?

[英]How to sort using a custom sort on arrays for JS?

Suppose if i have an array like [2,5,1,11,10,45] and a variable num = 99 .假设我有一个类似[2,5,1,11,10,45]的数组和一个变量num = 99 I want to sort the array based on the closest multiple(should also be the smallest multiple) to 99 or the number that can divide it with the least multiples.我想根据最接近的倍数(也应该是最小的倍数)到 99 或可以将其除以最小倍数的数字对数组进行排序。

So if we see the above array we can see that 99 can be completely divisible by 11 where the quotient is 9. Dividing my 10 would yield the divisor as 10. Similarly for others.因此,如果我们看到上面的数组,我们可以看到 99 可以被 11 完全整除,其中商为 9。除以我的 10 将产生除数为 10。其他人也是如此。 But when we divide 99/45 we have a quotient of 2.但是当我们除以 99/45 时,商为 2。

Since 1 is always a multiple of 99 or any number other than 99. It should be at the end of the array.因为 1 始终是 99 的倍数或 99 以外的任何数字。它应该位于数组的末尾。

In a nutshell, it should sort based on the least quotient.简而言之,它应该根据最小商进行排序。

So the output of the sort should be [45,11,10,5,2,1].所以排序的 output 应该是 [45,11,10,5,2,1]。

Try this: [2,5,1,11,10,45].sort((a, b) => 99 / b - 99 / a)试试这个: [2,5,1,11,10,45].sort((a, b) => 99 / b - 99 / a)

But if your logic only in dividing, u can just sort number:但是,如果您的逻辑仅在除法中,则您可以对数字进行排序:

[2,5,1,11,10,45].sort((a, b) => b - a)

cause than n is higher, than result of division will be smaller因为比n大,比除法的结果小

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

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