求使用Intl.Collator.compare排序JavaScript对象的示例
使用Intl.Collator对对象数组排序的示例
当然可以!其实你只需要在数组的sort方法里,用collator.compare去对比对象的目标属性(也就是你的name字段)就行了,核心逻辑和字符串数组排序是一致的,只是多了一步访问对象属性的操作。
先给你完整的可运行示例:
// 你的对象数组 var objs = [ {name: '1_Document', size: 40}, {name: '11_Document', size: 50}, {name: '2_Document', size: 60} ]; // 创建排序规则的collator var collator = new Intl.Collator(undefined, { numeric: true, sensitivity: 'base' }); // 对对象数组按name属性排序 objs.sort((a, b) => collator.compare(a.name, b.name)); // 输出排序后的结果 console.log(objs); // 结果会是: // [ // {name: '1_Document', size: 40}, // {name: '2_Document', size: 60}, // {name: '11_Document', size: 50} // ]
核心逻辑说明
Array.sort()接受的比较函数需要返回一个表示排序顺序的数字(负数、0、正数),而collator.compare(str1, str2)本身就会返回符合要求的数值。我们只需要把每个对象里要用来排序的属性(这里是a.name和b.name)作为参数传给collator.compare,就能实现按自然数字序对对象数组排序了。
对比你之前看到的字符串数组示例:
var myArray = ['1_Document', '11_Document', '2_Document']; myArray.sort(collator.compare);
本质上,字符串数组里直接传collator.compare是因为sort会把数组的每个元素直接传给比较函数;而对象数组需要我们手动提取出要比较的属性,再传给collator.compare。
内容的提问来源于stack exchange,提问作者user2004082
相关产品推荐
相关产品推荐

