使用lodash按值排序数组(整数)

时间:2022-12-25 19:16:23

I'm really struggling on that but I cannot find a solution.

我真的在努力,但我找不到解决方案。

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.

我有一个数组,我想按值(所有整数)排序​​。我想,好吧,让我们使用lodash,肯定必须有一个方便的功能。

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();

But unfortunately the return value does not seem to be an array anymore. myArray.length is undefined after the sorting.

但不幸的是,返回值似乎不再是一个数组。排序后,myArray.length未定义。

I found thousands of examples of lodash sorting array but always via key. https://lodash.com/docs#sortBy

我找到了成千上万的lodash排序数组的例子,但总是通过密钥。 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...

这不是那么困难,但不知怎的,我没有完成它......

Also sometimes I think that lodash documentation is a little complex. I'm probably just missing out an important detail...

有时我认为lodash文档有点复杂。我可能只是错过了一个重要的细节......

1 个解决方案

#1


44  

You can use the sortBy() function here. You don't have to specify a key, as it will fall back to identity().

您可以在此处使用sortBy()函数。您不必指定密钥,因为它将回退到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 ]

#1


44  

You can use the sortBy() function here. You don't have to specify a key, as it will fall back to identity().

您可以在此处使用sortBy()函数。您不必指定密钥,因为它将回退到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 ]