I'm trying to create a function that sorts an array based on a nested object value.
const customers = [
{
name: 'John',
displayOrder: [{ route1: 1 }, { route2: 3 }],
},
{
name: 'Julie',
displayOrder: [{ route1: 2 }, { route2: 1 }],
},
{
name: 'Betsy',
displayOrder: [{ route1: 3 }, { route2: 2 }],
},
];
function sortCustomers(customers, route) {
//enter amazing code here :P
//here is what I think could work, just don't know how to get the index number
customers.sort((a, b) => (a.displayOrder[?].route > b.displayOrder[?].route ? 1 : -1))
}
const route = 'route2';
sortCustomers(customers, route);
//desired output: [{Julie}, {Betsy}, {John}]
I want to use array.sort but I don't know how to dynamically generate the index for the appropriate route argument that is passed in.