0

I have an array of objects :

[{cat:A,size:2},
{cat:B,size:2},
{cat:B,size:1},
{cat:A,size:3},
{cat:C,size:5},
{cat:B,size:3}]

I'd like to sort this array first, by category, then by asc size in each category. The resulting array would be :

[{cat:A,size:2},
{cat:A,size:3},
{cat:B,size:1},
{cat:B,size:2},
{cat:B,size:3},
{cat:C,size:5}]

I am currently dividing the array in temporary subsets by cat, then sorting each of them by size and joining... But I have 100000+ values to sort and I am sure there's a better/faster way. I have underscore.js included in my project if that helps. The number of cat is dynamic ... Any suggestions?

3

2 Answers 2

3

Just perform both comparisons. You don't need to compare the sizes if the categories are different.

yourArray.sort(function(e1, e2) {
  if (e1.cat < e2.cat) return -1;
  if (e1.cat > e2.cat) return 1;
  // categories must be the same, so order by size
  if (e1.size < e2.size) return -1;
  if (e1.size > e2.size) return 1;
  return 0;
});
Sign up to request clarification or add additional context in comments.

Comments

0

When the categories are equal, the order is defined by the size values.
Else, the order is defined by the categories.
See it working here: https://codepen.io/JuanLanus/pen/bGNXYBL?editors=1011
Keep in mind that it works by returning negative, zero or positive values; no need to return +1 or -1.

let catSizes = [  
  { cat: 'A', size: 2 },  
  { cat: 'B', size: 2 },  
  { cat: 'B', size: 1 },  
  { cat: 'A', size: 3 },  
  { cat: 'C', size: 5 },  
  { cat: 'B', size: 3 }  
];  

  catSizes.sort( ( a, b ) => {  
    if( a.cat === b.cat ){ return a.size - b.size }  
    return a.cat > b.cat ? 1 : -1;  
  });````

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.