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?