使用lodash我希望能够通过几个键对下面的对象数组(但更大)进行排序,其中一些键嵌套在数组中:优先级为:
我也希望能够扭转上述情况。
我已查看lodash documentation,但看不到我的问题的解决方案:
[{
displayInGraph: true,
pinnedRow: true,
dateRange: [{
year: 2010,
income: 20000
}, {
year: 2011,
income: 30000
}, {
year: 2012,
income: 40000
}, {
year: 2013,
income: 44000
}]
},
{
displayInGraph: true,
pinnedRow: false,
dateRange: [{
year: 2010,
income: 20000
}, {
year: 2011,
income: 32500
}, {
year: 2012,
income: 50000
}, {
year: 2013,
income: 45200
}]
},
{
displayInGraph: true,
pinnedRow: false,
dateRange: [{
year: 2010,
income: 20400
}, {
year: 2011,
income: 38000
}, {
year: 2012,
income: 30000
}, {
year: 2013,
income: 45000
}]
},
{
displayInGraph: true,
pinnedRow: true,
dateRange: [{
year: 2010,
income: 21030
}, {
year: 2011,
income: 39000
}, {
year: 2012,
income: 44000
}, {
year: 2013,
income: 45400
}]
}
]

提前感谢您提供解决方案
答案 0 :(得分:1)
通过让迭代函数返回要排序的属性数组,可以使用lodash对对象中的多个属性进行排序。此示例将按属性a
排序,然后按属性b
排序,然后按属性sortkey
排序。
var input = [
{ a: 4, b: 5, data: 9, sortkey: "blue" },
{ a: 3, b: 9, data: 27, sortkey: "red" },
{ a: 3, b: 9, data: 4, sortkey: "green" },
{ a: 3, b: 3, data: 19, sortkey: "purple" },
{ a: 4, b: 3, data: 6, sortkey: "white" },
{ a: 5, b: 0, data: 0, sortkey: "orange" }
];
var output = _.sortBy(input, function(o) {
return [o.a, o.b, o.sortkey];
});
见小提琴:https://jsfiddle.net/mikeular/qog6h9ez/3/。
然后,您可以通过更新阵列来反转排序行为。例如,如果您希望a
升序,b
降序,sortkey
升序,则可以执行以下操作:
var output = _.sortBy(input, function(o) {
return [o.a, -1 * o.b, o.sortkey];
});
(我更喜欢-1 * o.b
而不是-o.b
来提升逆转的可见性。
看看它的表现与稍微清洁相比,这将是一个有趣的练习:
var output = _.sortBy(input, ['a', 'b', 'sortkey']);
......如果表现与你相关。
答案 1 :(得分:1)
Lodash有一个_.sortBy
方法,它接受第二个参数,一个字符串(作为sort属性的路径),或一个函数(返回sort属性)或其数组。因此,您可以使用排序函数数组对多个参数进行排序:
const myArray = [{
displayInGraph: true,
pinnedRow: true,
dateRange: [{
year: 2010,
income: 20000
}, {
year: 2011,
income: 30000
}, {
year: 2012,
income: 40000
}, {
year: 2013,
income: 44000
}]
},
{
displayInGraph: true,
pinnedRow: false,
dateRange: [{
year: 2010,
income: 20000
}, {
year: 2011,
income: 32500
}, {
year: 2012,
income: 50000
}, {
year: 2013,
income: 45200
}]
},
{
displayInGraph: true,
pinnedRow: false,
dateRange: [{
year: 2010,
income: 20400
}, {
year: 2011,
income: 38000
}, {
year: 2012,
income: 30000
}, {
year: 2013,
income: 45000
}]
},
{
displayInGraph: true,
pinnedRow: true,
dateRange: [{
year: 2010,
income: 21030
}, {
year: 2011,
income: 39000
}, {
year: 2012,
income: 44000
}, {
year: 2013,
income: 45400
}]
}
]
console.log(_.sortBy(myArray, [
item => (item.dateRange.find(range => range.year === 2012) || {income: 0}).income,
item => item.displayInGraph,
item => item.pinnedRow,
]));

<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
&#13;
最后,您可以使用内置数组.reverse
方法的javascript来反转结果。
答案 2 :(得分:1)
你试过sortBy吗?它可以接收用于执行排序的每个步骤的函数列表。
例如,你可以:
const year = 2012;
const getIncome = (obj) => _.find(obj.dateRange, {income: year});
_.sortBy(users, [getIncome, 'displayInGraph', 'pinnedRow']);