0

I am trying to sort an array of objects by a field that holds numeric value. And this console output is the result of calling:

console.log(_.sortBy( d, 'userid' ));

[Object, Object, Object]
0: Object
count: "6"
name: "Andrey"
userid: "1234"
__proto__: Object
1: Object
count: "9"
name: "Lucas"
userid: "1337"
__proto__: Object
2: Object
count: "30"
name: "M"
userid: "7800"

And it looks fine, just as I expect it to happen.

However when I call this:

console.log(_.sortBy( d, 'count' ));

Instead of seeing array of order count 6, count 9, count 30, I see this:

Array[3]
0: Object
count: "30"
name: "M"
userid: "7800"
__proto__: Object
1: Object
count: "6"
name: "Andrey"
userid: "1234"
__proto__: Object
2: Object
count: "9"
name: "Lucas"
userid: "1337"

Can anyone help me understand what is happening and how can I fix it?

3
  • 6
    I don't see any numeric values. They're all strings. "9" is different from 9, especially when it comes to comparisons Commented Jun 5, 2013 at 20:17
  • 1
    And it is sorting it correctly, "30" (the "3") is before "6", which is before "9". Commented Jun 5, 2013 at 20:19
  • 1
    You got lucky with your sort by userid, in that they're also alphabetically ascending order in addition to numerical ascending order. also put a userid in there with the value of "7" and you'll see what happens. Commented Jun 5, 2013 at 20:20

1 Answer 1

1

Use parseInt(obj.count) before you sort.

Sign up to request clarification or add additional context in comments.

1 Comment

I used this function when adding elements to my array. Thank you for an useful answer.

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.