0

I have an array of items.

var myArray = [
    {group: 'A', title: 'Title 1'},
    {group: 'B', title: 'Title 2'},
    {group: 'C', title: 'Title 3'},
    {group: 'A', title: 'Title 4'},
    {group: 'A', title: 'Title 5'},
    {group: 'B', title: 'Title 6'},
    {group: 'C', title: 'Title 7'}
];

I would like to sort array first by group, and inside a group sort by title (alphabetically).

I know that I could create different arrays for every group and then sort them, but I think that this should be done in one .sort function.

puppeteer701
  • 1,225
  • 3
  • 17
  • 33
  • You can do it using a comparator function. It's easy - try something. – MightyPork Sep 01 '14 at 15:58
  • 2
    Have you put the logic inside of a [`.sort`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) function? If so, what problems did you run into? – Andrew Whitaker Sep 01 '14 at 15:58

2 Answers2

2

Just sort by both properties, first the group, then the title

myArray.sort(function(a,b) {
    var res = a.group.localeCompare(b.group);
    if (res != 0) return res;
    return a.title.localeCompare(b.title);
});

FIDDLE

localeCompare will sort alphabetically, but note that Title 16 would come before Title 2 when doing an alphabetic sort.

adeneo
  • 312,895
  • 29
  • 395
  • 388
0

This should work:

myArray.sort(
    function( a, b ) {
        if ( a.group === b.group ) {
            if ( a.title < b.title ) {
                return -1;
            } else if ( a.title > b.title ) {
                return 1;
            } else return 0;
        } else if ( a.group < b.group ) {
            return -1;
        } else return 1;
    }
);

Just for reference MDN has plenty of info on the subject.

SimonR
  • 1,248
  • 9
  • 10