Apply array.sort() default algorithm to string properties of objects in an array
本问题已经有最佳答案,请猛点这里访问。
来自
The default sort order is built upon converting the elements into
strings, then comparing their sequences of UTF-16 code units values.
号
如果目标数组的元素是对象,并且我们希望将上述算法应用于
1 2 3 4 5 6 | const targetArray = [ { targetKey: 'March' }, { targetKey: 'Jan' }, { targetKey: 'Feb' }, { targetKey: 'Dec' } ] |
预期结果:
1 2 3 4 5 6 | [ { targetKey: 'Dec' }, { targetKey: 'Feb' }, { targetKey: 'Jan' }, { targetKey: 'March' } ] |
号
一些简单的解决方案?
警告:在这个问题中,我们不考虑按字母排序。我们需要订购适当的UTF-16代码单位值序列。
可以在目标键上使用带有string::localecompare()的
1 2 3 4 5 6 7 8 9 10 | const targetArray = [ { targetKey: 'March' }, { targetKey: 'Jan' }, { targetKey: 'Feb' }, { targetKey: 'Dec' } ]; targetArray.sort((a, b) => a.targetKey.localeCompare(b.targetKey)); console.log(targetArray) |
如果不想改变(修改)原始数组,可以使用
1 2 3 4 5 6 7 8 9 10 11 | const targetArray = [ { targetKey: 'March' }, { targetKey: 'Jan' }, { targetKey: 'Feb' }, { targetKey: 'Dec' } ]; let res = targetArray.slice(0).sort((a, b) => a.targetKey.localeCompare(b.targetKey)); console.log(targetArray) console.log(res); |
号
还可以使用析构函数assingment获取
1 2 3 4 5 6 7 8 9 | const targetArray = [ { targetKey: 'March' }, { targetKey: 'Jan' }, { targetKey: 'Feb' }, { targetKey: 'Dec' } ], res = targetArray.sort(({targetKey:a}, {targetKey:b}) => a.localeCompare(b)); console.log(res); |
你可以用
1 2 3 4 5 6 7 8 9 10 | const targetArray = [ { targetKey: 'March' }, { targetKey: 'Jan' }, { targetKey: 'Feb' }, { targetKey: 'Dec' } ]; let op = targetArray.sort(({targetKey:a},{targetKey:b})=>new Intl.Collator('en').compare(a,b)); console.log(op) |
。