-1

I have the following array:

var array = [{
    "name": "Item 1",
    "LineNumber": "10",
    "size": "5"
    },
    {
    "name": "Item 2",
    "LineNumber": "30",
    "size": "5"
    },
    {
    "name": "Item 3",
    "LineNumber": "30",
    "size": "4"
    },
    {
    "name": "Item 4",
    "LineNumber": "20",
    "size": "5"
    }]

Using the following, I am able to sort by line number:

      array.sort(function(a, b) {
        return a.LineNumber - b.LineNumber;
      });

In some situations with large data, I run into an issue where items will share the same line number, but their size will be different (ie. Item 2 and Item 3). I would like to first sort by the line number, and then order by size based on how the first sort is returned. Is it possible to achieve this in one sort compare function?

1
  • 1
    Do the first comparison, if they are equal fallback to a second comparison test and return that. Commented Oct 16, 2015 at 15:29

2 Answers 2

7

Try this:

array.sort(function(a, b) {
  if (a.LineNumber == b.LineNumber)
    return a.size - b.size;
  return a.LineNumber - b.LineNumber;
});
Sign up to request clarification or add additional context in comments.

Comments

0

You just need to add more logic to your sort function.

  array.sort(function(a, b) {
    if (a.LineNumber === b.LineNumber) {
         return a.size - b.size;
    }
    return a.LineNumber - b.LineNumber;
  });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.