如何在一个数组中分别对2个对象数组进行排序? 需要Lodash的解决方案。 谢谢。
按年份排序的数组示例:
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
}]]
按年份排序后所需的输出:
[[{
year: 2009,
name: "john",
value: 40
},
{
year: 2010,
name: "john",
value: 30
}
],
[{
year: 2015,
name: "bob",
value: 30
},
{
year: 2018,
name: "bob",
value: 40
}]]
答案 0 :(得分:2)
orderBy
应该足够
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 :(得分:1)
您可以在数组数组上使用map()
并在map函数中返回排序后的数组。
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)
答案 2 :(得分:0)
您需要映射数组并对其进行排序:
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)
答案 3 :(得分:0)
您可以使用_.partialRight()
和_.map()
到_.sortBy()
子数组生成函数:
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>
或使用lodash / fp并删除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>