After developing a utility function to sort an array of objects based on either ascending or descending order, I encountered an issue when sorting string properties. For example, if "age" is passed as the second argument, the ordering works correctly. However, when "job" is passed, nothing happens. The expected behavior was for it to alphabetically order by job titles (Engineer, Marketing, Sales). Any suggestions on how to resolve this issue or why it is happening?
const arrayOfObjects = [
{ firstName: 'Joe', job: 'Engineer', age: 22 },
{ firstName: 'Sam', job: 'Sales', age: 30 },
{ firstName: 'Claire', job: 'Engineer', age: 40 },
{ firstName: 'John', job: 'Marketing', age: 29 },
{ firstName: 'Susan', job: 'Engineer', age: 21 },
];
const orderByValue = (array, orderByItem, order) => array.sort((a, b) => {
if (order === 'descending') {
return b[orderByItem] - a[orderByItem];
} else {
return a[orderByItem] - b[orderByItem];
}
});
// console.log('order by age:', orderByValue(arrayOfObjects, 'age'));
console.log('order by job:', orderByValue(arrayOfObjects, 'job'));