I am working on sorting an array of objects based on multiple fields, typically around 3-4 fields. Some values within the objects may be undefined, and I need to ensure that these undefined values are considered as "earlier" in the sorting process, whether it is ascending or descending order. Currently, my code works well for descending sorting, but when it comes to ascending sorting, the undefined values end up at the bottom instead of at the top. These undefined values are always strings, and I am only able to use the .sort() method without any additional operations before or after it. Here is a snippet of my code:
[{id: "1", label: "Z", code: "Z"},
{id: "1", code: "A"},
{id: "2", label: "A",},
{id: "3", label: "A", code: "A"}]
.sort((a,b) => {
return a.id.localeCompare(b.id)
|| a.label.localeCompare(b.label)
|| a.code.localeCompare(b.code)
);