I have an array of objects. And in each cards object has a property names votedBy, which stores userId of people giving the vote. I want to sort the array by the length of property votedBy. Note: Some object don't have votedBy property.
[{
id: 'card1',
text: "Item1",
votedBy: {
userId1: true,
userId2: true
}
},
{
id: 'card2',
text: 'Item 1',
votedBy: {
userId3: true
}
},
{
id: 'card3',
text: 'Item 3'
},
{
id: 'card4',
text: "Item4",
votedBy: {
userId5: true,
userId6: true,
userId7: true
}
}]
I try to use Array.sort like this
array.sort((a,b) => Object.keys(b.votedBy).length - Object.keys(a.votedBy).length )
And it works only if each object has to have a votedBy property. But some of my objects doens't have that property.
The outcome should look like this
[{
{
id: 'card4',
text: "Item4",
votedBy: {
userId5: true,
userId6: true,
userId7: true
}
},
{
id: 'card1',
text: "Item1",
votedBy: {
userId1: true,
userId2: true
}
},
{
id: 'card2',
text: 'Item 1',
votedBy: {
userId3: true
}
},
{
id: 'card3',
text: 'Item 3'
},
]
Update
array.sort((a, b) => (
Boolean(b.votedBy) - Boolean(a.votedBy)
|| Object.keys(b.votedBy).length - Object.keys(a.votedBy).length
));
It works only if I have 1 object without sortedBy. If I have more than 1 object without sortedBy, there's an error
Uncaught TypeError: Cannot convert undefined or null to object
new test array should look like that
[{
id: 'card1',
text: "Item1",
votedBy: {
userId1: true,
userId2: true
}
},
{
id: 'card2',
text: 'Item 1',
votedBy: {
userId3: true
}
},
{
id: 'card3',
text: 'Item 3'
},
{
id: 'card4',
text: "Item4",
votedBy: {
userId5: true,
userId6: true,
userId7: true
}
},
{
id: 'card5',
text: 'Item 5'
} ]
Update 2
I manage to make it working by long and ugly code. Does anyone have nicer and shorter code ?
array.sort((a, b) => {
if (a.votedBy === undefined && b.votedBy === undefined)
return Boolean(b.votedBy) - Boolean(a.votedBy)
else if (a.votedBy === undefined)
return Object.keys(b.votedBy).length - Boolean(a.votedBy)
else if (b.votedBy === undefined)
return Boolean(b.votedBy) - Object.keys(a.votedBy).length
else return Object.keys(b.votedBy).length - Object.keys(a.votedBy).length
});