使用 lodash 按值对数组进行排序(整数) [英] Sort array with lodash by value (integer)
问题描述
我真的在这方面苦苦挣扎,但我找不到解决方案.
I'm really struggling on that but I cannot find a solution.
我有一个数组,我想按值(所有整数)对其进行排序.我想,好吧,让我们使用 lodash,肯定有一个方便的功能.
I have an array and I want to sort it by value (all integers). I thought, well let's use lodash, there sure must be a handy function for that.
虽然我不知道该怎么做.
Somehow I cannot figure out to do this though.
到目前为止,我得到了这个:
So far I got this:
myArray = [3, 4, 2, 9, 4, 2]
如果我使用此代码,我得到了结果:
I got a result if I used this code:
myArray = _(myArray).sort();
但不幸的是,返回值似乎不再是一个数组了.排序后 myArray.length 未定义.
But unfortunately the return value does not seem to be an array anymore. myArray.length is undefined after the sorting.
我发现了数千个 lodash 排序数组的示例,但总是通过键.https://lodash.com/docs#sortBy
I found thousands of examples of lodash sorting array but always via key. https://lodash.com/docs#sortBy
有人可以告诉我如何将以下返回结果作为数组获得吗?:
Can somebody tell my how I can get the following return result as an array?:
[2, 2, 3, 4, 4, 9]
这不会那么难,但不知怎的,我没有完成它......
It can't be that difficult, but somehow I don't get it done...
有时我也认为 lodash 文档有点复杂.我可能只是错过了一个重要的细节......
Also sometimes I think that lodash documentation is a little complex. I'm probably just missing out an important detail...
推荐答案
您可以在此处使用 sortBy() 函数.您不必指定密钥,因为它会回退到 identity().
You can use the sortBy() function here. You don't have to specify a key, as it will fall back to identity().
var myArray = [ 3, 4, 2, 9, 4, 2 ];
_.sortBy(myArray);
// → [ 2, 2, 3, 4, 4, 9 ]
_(myArray).sortBy().take(3).value();
// → [ 2, 2, 3 ]
这篇关于使用 lodash 按值对数组进行排序(整数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!