简体   繁体   中英

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 . 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.

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. But when we divide 99/45 we have a quotient of 2.

Since 1 is always a multiple of 99 or any number other than 99. It should be at the end of the array.

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].

Try this: [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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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