Given the following array of objects:
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"
},
]
I would like to sort it like the below example:
[
{ 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' }
]
Where I can say move the objects where unit === 'Main House' to the top of the other values that share the same name
I try the below to no avail
const result = arr.sort((c1, c2) => (c1.unit === 'Main House' || c2.unit === 'Main House') ? 1 : -1)