给定以下对象数组:
const arr = [
{
"unit": "Room 2",
"name": "House A"
},
{
"unit": "Room 1",
"name": "House A"
},
{
"unit": "Main House",
"name": "House A"
},
{
"unit": "Room 3",
"name": "House B"
},
{
"unit": "Room 1",
"name": "House B"
},
{
"unit": "Room 2",
"name": "House B"
},
{
"unit": "Main House",
"name": "House B"
},
]
我想按照以下示例对其进行排序:
[
{ unit: 'Main House', name: 'House A' },
{ unit: 'Room 1', name: 'House A' },
{ unit: 'Room 2', name: 'House A' },
{ unit: 'Main House', name: 'House B' },
{ unit: 'Room 1', name: 'House B' },
{ unit: 'Room 2', name: 'House B' },
{ unit: 'Room 3', name: 'House B' }
]
我可以说把物体移到哪里 unit === 'Main House'
到共享相同名称的其他值的顶部
我尝试下面的方法,但没有用
const result = arr.sort((c1, c2) => (c1.unit === 'Main House' || c2.unit === 'Main House') ? 1 : -1)
2条答案
按热度按时间csbfibhn1#
您可以按如下顺序检查条件:
yh2wf1be2#
排序
name
首先unit
第二个例外是"Main House"
登上顶峰。String#localeCompare
使排序比较更容易:可以通过使用逻辑运算符和类型强制来缩短: