简体   繁体   English

使用 Lodash 对数字字符串数组进行排序

[英]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.此代码对数组进行排序,但由于字段“rhid”的值是字符串,因此顺序被打乱了。 How can i sort as if "rhid" where int field.我怎样才能像“rhid”一样对 int 字段进行排序。

Thanks谢谢

sortBy can be used with a function instead of a property name. sortBy可以与函数而不是属性名称一起使用。

_.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:如果你想像@GunasekaranR 那样做多个字段,你也可以用箭头符号来做:

_.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.第二种方式使用first_val作为主要排序对象, second_val是决胜局。

if rhid is number then you can do like this如果 rhid 是数字那么你可以这样做

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

mentioned here 这里提到

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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