Intl.Collator for JS Objects

妖精的绣舞 提交于 2019-12-10 14:23:54

问题


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}];

回答1:


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);


来源:https://stackoverflow.com/questions/50566693/intl-collator-for-js-objects

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!