Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intl.Collator for JS Objects

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}];
like image 435
user2004082 Avatar asked May 28 '18 12:05

user2004082


1 Answers

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);
like image 71
AndreasRey Avatar answered Sep 30 '22 07:09

AndreasRey