I'm making a sorting function where sort by value will be dynamic and some values of properties in objects in the array can be false.
I Would like to use localeCompare
due to possible special characters etc.
As seen in the example it breaks if a false
value is in the middle of the array. I did try to implement optional changing but it does not work at all then:
return a.sortValue?.[1].localeCompare(b.sortValue?.[1])
The expected results Is:
for user_id
:
4
1
2
3
and partner_id
:
4
1
3
2
Sort value is always (when not false) in 1 index of the array.
And would like false
at the end, I still need it in the list...
Is this possible without making some custom sorting function?
let arr = [{
id: 1,
user_id: ["ignoreThis", 'B'],
partner_id: ["ignoreThis", 'B']
},
{
id: 2,
user_id: ["ignoreThis", 'D'],
partner_id: false
},
{
id: 3,
user_id: false,
partner_id: ["ignoreThis", 'D']
},
{
id: 4,
user_id: ["ignoreThis", 'A'],
partner_id: ["ignoreThis", 'A']
}
]
const sortBy = sortValue => {
arr.sort(function(a, b) {
return a[sortValue][1].localeCompare(b[sortValue][1])
})
}
sortBy('user_id')
arr.forEach(i => console.log(i.id))
sortBy('partner_id')
arr.forEach(i => console.log(i.id))
.as-console-wrapper {
min-height: 100% !important;
}
CodePudding user response:
You could check the value first and the sort by the wanted value. This approach needs a default empty string for using localeCompare
.
const
array = [{ id: 1, user_id: ["ignoreThis", 'B'], partner_id: ["ignoreThis", 'B'] }, { id: 2, user_id: ["ignoreThis", 'D'], partner_id: false }, { id: 3, user_id: false, partner_id: ["ignoreThis", 'D'] }, { id: 4, user_id: ["ignoreThis", 'A'], partner_id: ["ignoreThis", 'A'] }]
sortBy = key => array.sort((a, b) =>
!a[key] - !b[key] ||
(a[key]?.[1] || '').localeCompare(b[key]?.[1])
);
sortBy('user_id');
console.log(...array.map(({ id }) => id));
sortBy('partner_id');
console.log(...array.map(({ id }) => id));