11

I am not able to find any example of sorting objects using collator.compare anywhere. Can anyone provide ? All the documentation and examples so far I came across show array sorting as example below:

var myArray = ['1_Document', '11_Document', '2_Document'];        
var collator = new Intl.Collator(undefined, {numeric: true, sensitivity: 'base'});
myArray.sort(collator.compare)

Would be good to see how this works for objects like

var objs = [{name: '1_Document', size: 40}, {name: '11_Document', size: 50}, {name: '2_Document', size: 60}];
user2004082
  • 141
  • 2
  • 8

1 Answers1

24

You can sort array of objects with Intl.Collator by wrapping collator.compare into a function passing objects reference as arguments

var collator = new Intl.Collator(undefined, {
  numeric: true,
  sensitivity: 'base'
});

var objs = [{
  name: '1_Document',
  size: 40
}, {
  name: '11_Document',
  size: 50
}, {
  name: '2_Document',
  size: 60
}];

objs.sort(function(a, b) {
  return collator.compare(a.name, b.name)
});

console.log(objs);
jdlm
  • 6,327
  • 5
  • 29
  • 49
AndreasRey
  • 241
  • 2
  • 4