0

I'm using lodash, and here's some sample code:

var stuff = [{a: 100}, {a: 90}];

var res1 = _.sortBy(stuff, function(st) {
    return [st.a];
});

var res2 = _.sortBy(stuff, function(st) {
    return st.a;
});



console.log(res1);
console.log(res2);

This returns:

[{a: 90}, {a: 100}]
[{a: 100}, {a: 90}]

Why does it switch when an array is returned?

2 Answers 2

4

The sorting callback doesn't expect an array to be returned (why would it?) so it implicitly converts it to a string. Strings are sorted in alphabetical order. In this specific case, 9 is greater than 1, therefore "90" is greater than "100".

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

3 Comments

How would I do sort by multiple columns then?
I had a feeling this would be an XY problem. That's a different question, but you would pass an array of sorting functions to _.sortBy(), one for each column.
@Shamoon check my answer
1

sort by multiple columns

_.sortBy(data, ['key1', 'key2']);

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.