3

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.

2
  • Hi @beadle, usually people don't bluntly ask for implementations here on stackoverflow. Post your own solution approach and then we might have a look what's the concrete problem with it or how it might be improved. Commented Dec 18, 2020 at 17:53
  • Hey @Benjamin, thank you for letting me know! Commented Dec 18, 2020 at 20:34

2 Answers 2

2

You could find the order and take it as value for sorting.

function sortCustomers(customers, route) {
    const order = ({ displayOrder }) => displayOrder.find(o => route in o)[route];
    customers.sort((a, b) => order(a) - order(b));
    return customers;
}

const customers = [{ name: 'John', displayOrder: [{ route1: 1 }, { route2: 3 }] }, { name: 'Julie', displayOrder: [{ route1: 2 }, { route2: 1 }] }, { name: 'Betsy', displayOrder: [{ route1: 3 }, { route2: 2 }] }];

console.log(sortCustomers(customers, 'route2'));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

0

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) {
  const index = route == "route2" ? 1 : 0;
   let sorted = customers.sort((a, b) => {
    return a.displayOrder[index][route] - b.displayOrder[index][route]
  })
  
   // only listed name obj
    const result = sorted.map(obj => obj.name);
   
  return result;
}

const route = 'route2';

const result = sortCustomers(customers, route);
console.log(result)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.