Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array with lodash by value (integer)

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.

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.

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

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

like image 453
Merc Avatar asked Mar 09 '15 16:03

Merc


People also ask

How do you sort an array with Lodash?

sortBy() function is used to sort the array in ascending order. Parameters: This parameter holds the collection as a first parameter, Second parameter is optional. The second parameter is basically a function that tells how to sort. Return Value: It returns the sorted collection.

How do you use sortBy Lodash?

js. Lodash helps in working with arrays, collection, strings, objects, numbers etc. The _. sortBy() method creates an array of elements which is sorted in ascending order by the results of running each element in a collection through each iteratee.

Is Lodash sortBy stable?

Creates an array of elements, sorted in ascending order by the results of running each element in a collection thru each iteratee. This method performs a stable sort, that is, it preserves the original sort order of equal elements.

How do you sort an array in descending order?

To sort an array in Java in descending order, you have to use the reverseOrder() method from the Collections class. The reverseOrder() method does not parse the array. Instead, it will merely reverse the natural ordering of the array.


1 Answers

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 ] 
like image 188
Adam Boduch Avatar answered Sep 22 '22 22:09

Adam Boduch