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

3 Answers 3

28

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

_.sortBy(arrData, function (obj) {
    return parseInt(obj.rhid, 10);
});
Sign up to request clarification or add additional context in comments.

2 Comments

How can I sort by more than two fields and sort by desc with this implementation?
@GunasekaranR - in that case you can use this: sortBy(arrData, [function(obj) { return parseInt(obj.field1); }, function(obj) { return parseInt(obj.field2); }]);
8

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.

Comments

1

if rhid is number then you can do like this

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

mentioned here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.