Reputation: 23
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
}]]
Upvotes: 0
Views: 86
Reputation: 191986
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/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>
Upvotes: 0
Reputation: 36574
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)
Upvotes: 1
Reputation: 6749
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>
Upvotes: 2
Reputation: 8122
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)
Upvotes: 0