1

I am trying to sort an array of objects by two keys, where the first one is sorted in an ascending matter and the second is sorted by equality. What I attempted, sorted the array only by the first attribute:

var test_array = [{number: 1, color: "#EEEE23"},
                  {number: 4, color: "#FFFFFF"},
                  {number: 5, color: "#EEEE23"},
                  {number: 1, color: "#FFFFFF"},
                  {number: 6, color: "#CCCC23"},
                  {number: 1, color: "#EEEE23"},
                  {number: 2, color: "#EEEE23"},
                  {number: 3, color: "#FFFFFF"},
                  {number: 1, color: "#FFFFFF"},
                  {number: 2, color: "#FFFFFF"},
                  {number: 3, color: "#EEEE23"},
                  {number: 2, color: "#EEEE23"},
                  {number: 3, color: "#FFFFFF"},
                  {number: 2, color: "#FFFFFF"}]

test_array.sort(function(x,y){
    return x.number - y.number || x.color === y.color

My goal is to get the array to look like this, where the colors are also sorted:

var test_array = [{number: 1, color: "#EEEE23"},
                  {number: 1, color: "#EEEE23"},
                  {number: 1, color: "#FFFFFF"},
                  {number: 1, color: "#FFFFFF"},
                  {number: 2, color: "#EEEE23"},
                  {number: 2, color: "#EEEE23"},
                  {number: 2, color: "#FFFFFF"},
                  {number: 2, color: "#FFFFFF"},
                  {number: 3, color: "#EEEE23"},
                  {number: 3, color: "#FFFFFF"},
                  {number: 3, color: "#FFFFFF"},
                  {number: 4, color: "#FFFFFF"},
                  {number: 5, color: "#EEEE23"},
                  {number: 6, color: "#CCCC23"}]

Is my solution too naive and using equality in to sort does not work that easily?

1
  • The second one cannot be used that way right? Commented Jun 19, 2018 at 21:40

1 Answer 1

6

Using an equality comparison does not make sense because the sort() function expects the return value to be a number; equality comparison returns true or false. Instead, you can use the String .localeCompare() method:

return x.number - y.number || x.color.localeCompare(y.color);

The .localeCompare() function does exactly what you want, returning -1, 0, or 1 based on the lexicographic ordering of the strings.

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

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.