Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sort array of numeric strings with Lodash

_.sortBy(arrData, "rhid");

This code sorts array but as the values of field "rhid" are strings the order is messed up. How can i sort as if "rhid" where int field.

Thanks

like image 931
Leonel Matias Domingos Avatar asked Jan 11 '16 14:01

Leonel Matias Domingos


People also ask

How to sort array in Lodash?

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 does sortBy work?

sortBy() function is used to sort all the elements of the list in ascending order according to the function given to it as a parameter. Passing the array with a function which returns the number and it will sort the array in ascending order and return an array. The array can be both of numeric values and string values.


1 Answers

sortBy can be used with a function instead of a property name.

_.sortBy(arrData, function (obj) {
    return parseInt(obj.rhid, 10);
});
like image 120
Gabriel Negut Avatar answered Oct 11 '22 17:10

Gabriel Negut