I have an array of objects like so:
[
{
required: false,
sort: 1
},
{
required: true,
sort: 2
},
{
required: false,
sort: 3
},
]
I want to sort it by required DESC, sort ASC. How do you do this?
The result I am looking for is:
[
{
required: true,
sort: 2
},
{
required: false,
sort: 1
},
{
required: false,
sort: 3
},
]
Currently tried with this, which doesnt work. It correctly puts required first, but then ignores sort for the required items:
arr.sort((a, b) => {
if (a.required) return -1
return a.sort - b.sort
})
You can subtract the second required (2) from the first (1) when comparing. If they are the same value, you can logical-OR the left (1) and right (2) sort values.
const data = [
{ required: false , sort: 1 },
{ required: true , sort: 2 },
{ required: false , sort: 3 },
];
const sorted = data.sort((
{ required: r1, sort: s1 },
{ required: r2, sort: s2 }
) => r2 - r1 || s1 - s2);
console.log(sorted);
.as-console-wrapper { top: 0; max-height: 100% !important }
In JavaScript, subtracting booleans results in an integer value that is useful for sorting.
true - true // 0 (no change)
true - false // +1 (sink to bottom)
false - true // -1 (float to top)
false - false // 0 (no change)