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
}]]
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>
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)
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)
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.