1

I am trying to figure a way in JS to sort an array without actually changing the order of the elements but have more like a "grouping" feature.

Sample Data:

[
  {group: 'test',  title: 'A'},
  {group: 'test',  title: 'B'},
  {group: 'test2', title: 'C'},
  {group: 'test',  title: 'D'}
]

My idea is to do an [].sort() the way that my final order is:

[
  {group: 'test',  title: 'A'},
  {group: 'test',  title: 'B'},
  {group: 'test',  title: 'D'},
  {group: 'test2', title: 'C'}
]

Means: I did not change the order of the first two items but only switched #3 and #4 because of their group. If I'd do with a classical localeCompare, I'd end up with my groups being restored based on their value which is not what I want, their order should be kept.

EDIT: Considering the answers, I want to re-clarify that I do not want to change the order of the groups, means they should not be alphabetically sorted but instead, they should be groupped by the order they appear.

anderswelt
  • 1,482
  • 1
  • 12
  • 23
  • possible duplicate of [Sorting an array of JavaScript objects](http://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects) – Gabriele Petrioli Dec 12 '13 at 10:26
  • possible duplicate of [Sorting objects in an array by a field value in JavaScript](http://stackoverflow.com/questions/1129216/sorting-objects-in-an-array-by-a-field-value-in-javascript) – Louis Brunner Dec 12 '13 at 10:28
  • 2
    Aren't you just sorting by the `group` value, or am I missing something? – Aioros Dec 12 '13 at 10:32
  • About stable sort, check this: http://stackoverflow.com/questions/3026281/array-sort-sorting-stability-in-different-browsers. – Andrew Dec 12 '13 at 10:40

3 Answers3

0

You need to provide a custom comparison function to Array.sort

var a = [
  {group: 'test', title: 'A'},
  {group: 'test', title: 'B'},
  {group: 'test2', title: 'C'},
  {group: 'test', title: 'D'}
];

function myComparisonFunction(a1, b1) {
    return a1.group < b1.group ? -1 : a1.group === b1.group ? 0 : 1;
}

a.sort(myComparisonFunction);

console.log(a);
robbmj
  • 16,085
  • 8
  • 38
  • 63
0

Try this:

function compare(b,c) {
  if (b.title < c.title)
     return -1;
  if (b.title > c.title)
    return 1;
  return 0;
}

objs.sort(compare);
Mr.G
  • 3,413
  • 2
  • 16
  • 20
0

You can try with a compare function similar to this:

function comp(a, b) {
  if (a.group == b.group) {
    return a.title < b.title ? -1 : a.title == b.title ? 0 : 1;
  }
  return a.group < b.group ? -1 : 1;
}

youArray.sort(comp)

If I understood your question correctly, you want to sort on groups first, but then sort on title if your groups are the same.

mamapitufo
  • 4,680
  • 2
  • 25
  • 19