Search code examples
javascriptsortingecmascript-6lodash

ES6, Lodash sortBy 2 level array of objects


Can't figure out how to sort this kind of structure:

[
  0: { text: 'Lorem', 'children': [ 0: { text: 'Ipsum of Lorem' } ... ] }
  ...
]

I can only sort by the first level like this: _.sortBy(myArray,'text')

I need something like _.sortBy(myArray, ['text','children.text']) this obviously doesn't work.

I need to sort by children.text of each item.


Solution

  • You should loop over the children array.

    const myArray = [{ text: 'ZLorem', 'children': [{ text: 'Ipsum2' }, { text: 'Apsum2' }] },{ text: 'Lorem', 'children': [{ text: 'Ipsum1' }, { text: 'Zpsum1' }] }],
          result = _.sortBy(myArray, 'text');
          
    result.forEach(o => {
      if (o.children) 
        o.children = _.sortBy(o.children, 'text');
    });
    
    console.log(result);
    .as-console-wrapper { min-height: 100%; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>