简体   繁体   中英

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

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

_.sortBy(arrData, function (obj) {
    return parseInt(obj.rhid, 10);
});

This can be achieved using arrow notation like:

_.sortBy(arrData, (obj) => parseInt(obj.val, 10));

If you want to do more than one field like @GunasekaranR asked, you can also do it with arrow notation:

_.sortBy(arrData, [
  (obj) => parseInt(obj.first_val, 10),
  (obj) => parseInt(obj.second_val, 10)
]);

The second way uses first_val as the main sorting object, with second_val being the tie breaker.

if rhid is number then you can do like this

orderBy(
      arrData,
      function (o) {
        return new Number(o.rhid);
      },
      ["asc"]
    ),

mentioned here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM