Search code examples
javascriptarrayssortingunderscore.jslodash

sorting an arrray with 2-3 nests javascript/lodash


Unable to understand how to sort this kind of data which has array inside nested array...

var data = {
   d1: [{
      nest1: {a:5, b:2},
      nest2: {a:3, b:1},
   }],
   d3: [{
      nest1: {a:7, b:9},
      nest2: {a:1, b:22},
   }],
   d2: [{
      nest1: {a:1, b:9},
      nest2: {a:11, b:22},
   }],
}

so basically, want to sort by a, b, key.

So First of all, I have iterated all objects to get an array(to be able to sort by key)

Now data looks like (just example)

data = [{
   key: "d1",
   obj: [{
      nest1: {a:1, b:2},
      nest2: {a:3, b:12},
   }]}],
  [{
   key: "d2",
   obj: [{
      nest1: {a:11, b:12},
      nest2: {a:13, b:22},
   }]}]

so now I can sort by key easily -

_.orderBy(vm.summaryData, 'key')

but still confused, how to sort by data.obj.nest1.a ??

Expectation: sort by key itself:

data = {
   d1: [{
      nest1: {a:5, b:2},
      nest2: {a:3, b:1},
   }],
   d2: [{
      nest1: {a:1, b:9},
      nest2: {a:11, b:22},
   }],
   d3: [{
      nest1: {a:7, b:9},
      nest2: {a:1, b:22},
   }],
}

Expectation: sort by nest1.a:

data = {
   d2: [{
      nest1: {a:1, b:9},
      nest2: {a:11, b:22},
   }],
   d1: [{
      nest1: {a:5, b:2},
      nest2: {a:3, b:1},
   }],
   d3: [{
      nest1: {a:7, b:9},
      nest2: {a:1, b:22},
   }],
}

Expectation: sort by nest2.a:

data = {
   d3: [{
      nest1: {a:7, b:9},
      nest2: {a:1, b:22},
   }],
   d1: [{
      nest1: {a:5, b:2},
      nest2: {a:3, b:1},
   }],
   d2: [{
      nest1: {a:1, b:9},
      nest2: {a:11, b:22},
   }],
}

and so on...nest1.b, nest2.b.....


Solution

  • You could take the path to the property for sorting with a string, separated by dots for sorting.

    function convert(object) {
        return Object
            .keys(object)
            .map(function (key) {
                return { key: key, obj: object[key] };
            });
    }
    
    var data = { d1: { nest1: { a: 1, b: 2 }, nest2: { a: 3, b: 12 } }, d2: { nest1: { a: 11, b: 1 }, nest2: { a: 13, b: 22 } } },
        result = convert(data);
    
    console.log(_.orderBy(result, 'obj.nest1.b'));
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>