Sort with JavaScript Comparator

Comparators are used to sort the user defined objects. It gives you flexibility to sort the objects in multiple ways. For example you can sort strings by alphabetical order, or by their lengths. If you have a Country class with id and name, you can sort by the id, name, or combinations. The JavaScript comparator can be defined as a function. You can declare it as const and assign a name to it. Then you can call the sort() method with this name as the argument.

If you are not familiar with the syntax of JavaScript Comparator, you can applying the examples here as template.

Output:
[
Country { id: 1, name: ‘Kenya’ },
Country { id: 2, name: ‘Mexcico’ },
Country { id: 2, name: ‘America’ },
Country { id: 3, name: ‘Spain’ },
Country { id: 4, name: ‘Sandi arabia’ }
]
sort countries by name alphabetically :
[
Country { id: 2, name: ‘America’ },
Country { id: 1, name: ‘Kenya’ },
Country { id: 2, name: ‘Mexcico’ },
Country { id: 4, name: ‘Sandi arabia’ },
Country { id: 3, name: ‘Spain’ }
]
sort countries by id and name :
[
Country { id: 1, name: ‘Kenya’ },
Country { id: 2, name: ‘America’ },
Country { id: 2, name: ‘Mexcico’ },
Country { id: 3, name: ‘Spain’ },
Country { id: 4, name: ‘Sandi arabia’ }
]


Sort with lambda comparator
Coding questions series (YouTube)

Comments are closed