Search code examples
javascriptlodash

Order By custom order in object inside property


I need to sort an array of objects by a property of a sub-object:

foo = [
  {
    bar: {
      order: "hello" 
    } 
  },
  {
    bar: {
      order: "something" 
    } 
  },
  {
    bar: {
      order: "else" 
    } 
  },
]

If I want the order of the foo objects to based on a custom order (not alphabetical!) set by order values like

{ "something": 1, "hello": 2, "else": 3 }

with something like _orderBy(foo, indexOfMyCustomOrder, 'desc'), how can I achieve this? Or do I need to separate this logic into two functions?


Solution

  • Define indexOfMyCustomOrder as follows:

    const indexOfMyCustomOrder = o => order[o.bar.order];
    

    ... where the order variable should be the object that defines the sequence for each possible value of the order property.

    See snippet:

    const foo = [{bar:{order:"hello"}},{bar:{order: "something"}},{bar:{order:"else"}}];
    const order = { "something": 1, "hello": 2, "else": 3 };
    
    const result = _.orderBy(foo, o => order[o.bar.order]);
    
    console.log(result);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>