首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据另一个键排序属性的max/min

问根据另一个键排序属性的max/min
EN

Stack Overflow用户
提问于 2016-08-11 04:14:03
回答 2查看 55关注 0票数 0

假设有一个json对象数组,如下所示:

代码语言:javascript
复制
[{ customerId:1, orderId:1-1, orderAmount:100
   customerId:2, orderId:2-1, orderAmount: 125
   customerId:1, orderId: 1-2, orderAmount: 112
  ............
}]

我想找出每一位顾客的最高(或最低)订单

代码语言:javascript
复制
[{customerId:1, orderId:1-2, orderAmount:112},{.....}]

是否可以使用任何语言结构(我正在使用Node.js)或Node.js。我认为,无论是按customerId排序还是按orderAmount排序,在存档中都是简单明了的,但不是上述组合。

我唯一能想到的其他方法是双forEachOf (异步)循环,这可能不是很有效。

任何帮助都是感激的..。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-08-11 21:28:59

将orderBy与order升序或降序结合使用,以确定是最低还是最高。按custormerId分组,并从每个客户订单中获取第一项:

​

代码语言:javascript
复制
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);
代码语言:javascript
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.2/lodash.min.js"></script>

​

票数 0
EN

Stack Overflow用户

发布于 2016-08-11 17:28:18

_.sortBy允许您指定要排序的字段数组。您可以使用:

代码语言:javascript
复制
var output = _.sortBy(input, ['customerId', 'orderAmount']);

如果还希望将对象分组到数组中,以便更容易地为每个customerId找到最大和最小值,则可以使用_.groupBy,然后排序。

代码语言:javascript
复制
var output = _.mapValues(_.groupBy(input, 'customerId'), function(val) {
  return _.sortBy(val, 'orderAmount');
});

这将产生如下结构:

代码语言:javascript
复制
{
  "1": [
    { customerId: 1, orderId: "1-2", orderAmount: 112 },
    { customerId: 1, orderId: "1-1", orderAmount: 100 }
  ],
  "2": [
    { customerId: 2, orderId: "2-1", orderAmount: 125 }
  ]
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38887161

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档