Recently encountered an algorithm problem, which requires sorting an array of key:value according to the value pair (the value value here can refer to multiple rows), the logic of a hotel's rating system.
Name Hygiene User Experience Security
A x1 y1 z1
B x2 y2 z2
... ... ... ...
Similar to the above, then First, sort the hygiene. After the hygiene is sorted, select the top three from the hygiene ranking. Select the top three people selected previously. Sort according to the user experience. Select the top two according to the user experience. Sort according to the security. Select the security. of first place.
Finally output the first place.
It feels like they are actually similar, but I have checked the information and the map function, but I still can’t understand how to do it. Please give me some advice. (ps: I obviously feel that my algorithm is not bad, but every time I encounter a slightly more complicated algorithm, I get confused. Not long after I entered the front-end pit, I have gone through the basic js-related codes), please help me Solve doubts.
First of all, is this your topic or project? If it's a real project, you can use
lodash
的sortBy
to sort the objects in the list.Suppose your hotel list model simplifies to:
The current requirement is to sort the objects in the list first by a, then by b, and then by c. To implement it is:
If the bigger the score, the better, then it should be in reverse order
As mentioned in the question, if you want to pick out 3, 2, and 1, you don’t need to sort all the results every time.
If it is an interview question, you still need to complete
sortBy
这个函数, 可以简单利用Array#sort
implementation:Note:
sortBy
要实现成稳定排序, 即两个分数一致的对象,排序前后相对位置要保持不变。当然直接使用上
Array#sort(func)
This function is also very convenient.