When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
If the result is negative, a is sorted before b.
If the result is positive, b is sorted before a.
If the result is 0, no changes are done with the sort order of the two values.
Example:
The compare function compares all the values in the array, two values at a time (a, b).
When comparing 40 and 100, the sort() method calls the compare function(40, 100).
The function calculates 40 - 100 (a - b), and since the result is negative (-60), the sort function will sort 40 as a value lower than 100.
You can use this code snippet to experiment with numerically and alphabetically sorting:
So based on that (even though its kinda ugly):
cards.sort(compare);
function compare(a, b) {
if(b.type.method == "dictate") return -1000
if(a.type.method == "listen" && b.type.method !== "listen") return -1.5
if(a.type.method === "listen" && b.type.method === "listen")
return a.reference.length - b.reference.length
}
const cards = [
{
type: { method: 'listen' },
reference: ['destroyed', 'word 2']
},
{
type: { method: 'synonym' },
reference: ['destroyed']
},
{
type: { method: 'listen' },
reference: ['destroyed']
},
{
type: { method: 'dictate' },
reference: ['destroyed 1']
},
{
type: { method: 'listen' },
reference: ['destroyed', 'word 2', 'type 3']
},
{
type: { method: 'synonym' },
reference: ['destroyed']
},
{
type: { method: 'listen' },
reference: ['destroyed', 'listen']
},
{
type: { method: 'dictate' },
reference: ['destroyed']
},
{
type: { method: 'listen' },
reference: ['destroyed', 'listen']
},
]