0

I have a JSON object that I want to sort:

obj = [
  { name: 'John 1'},
  { name: 'John 5'},
  { name: 'John 3'},
  { name: 'John 10'},
  { name: 'John 7'},
  { name: 'John 9'},
  { name: 'John 2'},
  { name: 'John 4'},
  { name: 'John 8'},
  { name: 'John 6'}
]

To sort the items I have the following function:

obj.sort(sortByKey('name'));

function sortByKey(key) {
  return function(a, b) {    
    if (a[key].toLowerCase() > b[key].toLowerCase()) {    
      return 1;    
    } else if (a[key].toLowerCase() < b[key].toLowerCase()) {    
      return -1;    
    }    
    return 0;    
  }
}

Problem is that I am getting the following response:

[
  { name: 'John 1'},
  { name: 'John 10'},
  { name: 'John 2'},
  { name: 'John 3'},
  { name: 'John 4'},
  { name: 'John 5'},
  { name: 'John 6'},
  { name: 'John 7'},
  { name: 'John 8'},
  { name: 'John 9'}
]

This is the expected behavior when we sort string, but I want the response to put John 10 after John 9 as Windows do with files.

enter image description here

Johnathan Barclay
  • 18,599
  • 1
  • 22
  • 35
Danilo Körber
  • 858
  • 1
  • 7
  • 27

0 Answers0