There is an array:
const array =
[
{ name: 'Skill 3', sortOrder: 3 },
{ name: 'Skill 2', sortOrder: null },
{ name: 'Skill 4', sortOrder: 2 },
{ name: 'Skill 1', sortOrder: null },
{ name: 'Skill 5', sortOrder: 1 },
]
I need to sort it so that the elements with null values appear at the bottom of the array and sort them by name.
The code I am tormenting with:
sortSkills() {
this.skills.sort((a, b) => {
if (a.sortOrder === b.sortOrder) {
return 0;
} else if (a.sortOrder === null) {
return 1;
} else if (b.sortOrder === null) {
return -1;
} else if (a.sortOrder < b.sortOrder) {
return -1;
} else if (a.sortOrder > b.sortOrder) {
return 1;
}
});
}
Code that works but has a lot of loops in it
const nullValuesArray = [];
const numericValuesArray = [];
this.skills.forEach((el) => {
if (el.sortOrder === null) {
nullValuesArray.push(el);
} else {
numericValuesArray.push(el);
}
});
nullValuesArray.sort((a, b) => {
return a.name.localeCompare(b.name);
});
numericValuesArray.sort((a, b) => {
return a.sortOrder - b.sortOrder;
});
this.skills = numericValuesArray.concat(nullValuesArray);