I am trying to sort array by three columns. Below is my sample array. Sometime, the column can be null too, so I do a checking in my sort function. However, now I would like to sort the name first and then salary and then bonus. How can I achieve that?
let employees = [
{name: 'John', salary: 90000, bonus: 1000},
{name: 'David', salary: 90000, bonus: 1200},
{name: 'Ana', salary: 80000, bonus: 3000}
];
// Code for sorting salary first and then bonus:
function sort(a,b) {
if (a.salary=== null && b.salary=== null ){
return a.bonus- b.bonus;
}
else if (a.salary!== null && b.salary=== null ){
return -1;
}
else if (a.salary=== null && b.salary!== null){
return 1;
}else if (a.salary!== null && b.salary!== null){
return a.salary- b.salary;
}
else {
return 1;
}
}
employees.sort(sort);
console.log(employees);