【发布时间】:2021-08-04 10:34:53
【问题描述】:
我需要排序字符串。但是当它在字符串中找到空格时,它不会正确排序。我怎样才能让它不对空间进行排序?
const array = [
{ attributes: { name: 'abcd efg' } },
{ attributes: { name: 'Übd cd' } },
{ attributes: { name: 'Ku cdf' } },
{ attributes: { name: 'äb' } },
{ attributes: { name: 'abc' } }
]
array.sort((a, b) => {
if (a.attributes.name.toUpperCase()
.localeCompare(b.attributes.name.toUpperCase(), 'de', { sensitivity: 'base' })) { return -1 }
if (b.attributes.name.toUpperCase()
.localeCompare(b.attributes.name.toUpperCase(), 'de', { sensitivity: 'base' })) { return 1 }
return 0
})
console.log('typeof array', array)
我希望看到:
[
{ attributes: { name: 'abc' } },
{ attributes: { name: 'abcd efg' } },
{ attributes: { name: 'äb' } },
{ attributes: { name: 'Ku cdf' } },
{ attributes: { name: 'Übd cd' } }
]
【问题讨论】:
-
在转换为大写之前删除空格怎么样?
name.replace(/\s+/g, '').toUpperCase()? -
预期结果是什么?
-
@evolutionxbox 删除空格但不影响排序。
-
@SalmanA 我编辑我的问题以查看。
-
不确定你为什么在
if中使用localeCompare的结果。这对于 1 和 -1 都是真实的。另外,你的第二个localeCompare,两者都有b.attributes
标签: javascript arrays sorting string-comparison