假设有一个json对象数组,如下所示:
[{ customerId:1, orderId:1-1, orderAmount:100
customerId:2, orderId:2-1, orderAmount: 125
customerId:1, orderId: 1-2, orderAmount: 112
............
}]我想找出每一位顾客的最高(或最低)订单
[{customerId:1, orderId:1-2, orderAmount:112},{.....}]是否可以使用任何语言结构(我正在使用Node.js)或Node.js。我认为,无论是按customerId排序还是按orderAmount排序,在存档中都是简单明了的,但不是上述组合。
我唯一能想到的其他方法是双forEachOf (异步)循环,这可能不是很有效。
任何帮助都是感激的..。
发布于 2016-08-11 21:28:59
将orderBy与order升序或降序结合使用,以确定是最低还是最高。按custormerId分组,并从每个客户订单中获取第一项:
function getMinMax(orders, min) { // orders - array of orders, min - true if minimum, undefined / false if maximum
var order = !!min ? 'asc' : 'desc';
return _(orders)
.orderBy('orderAmount', order) // orderBy the orderAmount property, with order determining highest or lowest
.groupBy('customerId') // group all orders by customer id
.map(function(orders) { // create a new array of just the 1st order of each customer, which will be the highest or the lowest
return orders[0];
}).value();
}
var orders = [{
customerId: 1,
orderId: '1-1',
orderAmount: 100
}, {
customerId: 2,
orderId: '1-2',
orderAmount: 128
}, {
customerId: 2,
orderId: '1-3',
orderAmount: 12
}, {
customerId: 1,
orderId: '1-3',
orderAmount: 113
}, {
customerId: 2,
orderId: '1-1',
orderAmount: 125
}, {
customerId: 2,
orderId: '4-1',
orderAmount: 11
}, {
customerId: 1,
orderId: '1-2',
orderAmount: 25
}];
var highestOrders = getMinMax(orders);
console.log('highestOrders', highestOrders);
var lowesetOrders = getMinMax(orders, true);
console.log('lowesetOrders', lowesetOrders);<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.2/lodash.min.js"></script>
发布于 2016-08-11 17:28:18
_.sortBy允许您指定要排序的字段数组。您可以使用:
var output = _.sortBy(input, ['customerId', 'orderAmount']);如果还希望将对象分组到数组中,以便更容易地为每个customerId找到最大和最小值,则可以使用_.groupBy,然后排序。
var output = _.mapValues(_.groupBy(input, 'customerId'), function(val) {
return _.sortBy(val, 'orderAmount');
});这将产生如下结构:
{
"1": [
{ customerId: 1, orderId: "1-2", orderAmount: 112 },
{ customerId: 1, orderId: "1-1", orderAmount: 100 }
],
"2": [
{ customerId: 2, orderId: "2-1", orderAmount: 125 }
]
}https://stackoverflow.com/questions/38887161
复制相似问题