按值对Lodash数组进行排序(整数) [英] Sort array with lodash by value (integer)

查看:118
本文介绍了按值对Lodash数组进行排序(整数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的很努力,但是我找不到解决办法.

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排序数组的示例,但是总是通过key进行的. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆