I've created a util function to sort an array of objects in either ascending or descending order which accepts the property. It appears to work fine for sorting numeric, but not string properties. E.g. in the below, if you pass in "age" as the second argument it order correctly, however if you pass in "job" as the second argument, nothing happens. I was hoping it would order alphabetically by job (Engineer, Marketing, Sales). Any ideas how to fix this / 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'));
-to do for strings?a[orderByItem] > b[orderByItem]but doesn't work either.