How to sort separately 2 arrays of objects inside an array ? A solution with Lodash needed. Thank you.

Example of Array to sort by year:

var objects = [[{
      year: 2010,
      name: "john",
      value: 30
    },
    {
      year: 2009,
      name: "john",
      value: 40
    }
  ],
  [{
      year: 2018,
      name: "bob",
      value: 40
    },
    {
      year: 2015,
      name: "bob",
      value: 30
    }]]

Desired output after sorting by year:

[[{
      year: 2009,
      name: "john",
      value: 40
    },
    {
      year: 2010,
      name: "john",
      value: 30
    }
  ],
  [{
      year: 2015,
      name: "bob",
      value: 30
    },
    {
      year: 2018,
      name: "bob",
      value: 40
    }]]

4 Answers

2
Krzysztof Krzeszewski On Best Solutions

orderBy on every sub collection should suffice

var objects = [
[{
year: 2010,
name: "john", 
value: 30
},
{
year: 2009,
name: "john",
value: 40
}],
[{
year: 2018,
name: "bob", 
value: 40
},
{
year: 2015,
name: "bob",
value: 30
}]
]

console.log(objects.map(subObject => _.orderBy(subObject, "year")));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

1
Maheer Ali On

You can use map() on array of arrays and return the sorted array in map function.

var arr = [[{year:2010,name:"john",value:30},{year:2009,name:"john",value:40}],[{year:2018,name:"bob",value:40},{year:2015,name:"bob",value:30}]];


const res = arr.map(x => x.slice().sort((a,b) => a.year - b.year));
console.log(res)

0
Amit Baranes On

You need to map the array and than sort it :

const objects = [
[{
year: 2010,
name: "john", 
value: 30
},
{
year: 2009,
name: "john",
value: 40
}],
[{
year: 2018,
name: "bob", 
value: 40
},
{
year: 2015,
name: "bob",
value: 30
}]
] 

const sorted = objects.map(r=>r.sort((a,b)=>a.year - b.year));

console.log(sorted)

0
Ori Drori On

You can generate a function with _.partialRight() and _.map() to _.sortBy() the sub arrays:

const { partialRight: pr, map, sortBy } = _;

const sortSubArrays = pr(map, arr => sortBy(arr, 'year'));

const objects = [[{year:2010,name:"john",value:30},{year:2009,name:"john",value:40}],[{year:2018,name:"bob",value:40},{year:2015,name:"bob",value:30}]];

const output = sortSubArrays(objects);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>

Or use lodash/fp and drop the partialRight:

const { map, sortBy } = _;

const sortSubArrays = map(sortBy('year'));

const objects = [[{year:2010,name:"john",value:30},{year:2009,name:"john",value:40}],[{year:2018,name:"bob",value:40},{year:2015,name:"bob",value:30}]];

const output = sortSubArrays(objects);

console.log(output);
.as-console-wrapper { max-height: 100% !important; top: auto; }
<script src='https://cdn.jsdelivr.net/g/[email protected](lodash.min.js+lodash.fp.min.js)'></script>