0

I build an array like this

result.push({ id: id, reference: sometext });

Now I want to sort this array by reference, which has some text.

I tried this:

result.sort(function(a,b) {
    return result[a]-result[b];
});

This

[ { id: 1, reference: 'banana' },
{ id: 2, reference: 'apple' } ]

should get

[ { id: 2, reference: 'apple' },
{ id: 1, reference: 'banana' } ]
user3142695
  • 15,844
  • 47
  • 176
  • 332
  • Possible duplicate of [Sort array of objects by string property value in JavaScript](http://stackoverflow.com/questions/1129216/sort-array-of-objects-by-string-property-value-in-javascript) – Andreas Wenger Nov 15 '15 at 10:59

2 Answers2

0

Do it like this instead:

result.sort(function(a,b) {
    return a.reference < b.reference ? -1 : 1;
});
andrrs
  • 2,289
  • 3
  • 17
  • 25
0

Try this.

result.sort(function(a,b) {
// Compare reference
if(a.reference < b.reference) {
   // a's reference is lesser than the one in b
   return -1;
} else if (a.reference == b.reference) {
   // Both reference params are equal
   return 0;
} else {
   // a's reference is greater than that of b
   return 1
}
});

This will return a sorted version of the results array.

kkaosninja
  • 1,301
  • 11
  • 21