Subu Subu - 3 months ago 13
Node.js Question

Get max/min of an attribute sorted based on another key

Suppose I have an array of json objects like:

[{ customerId:1, orderId:1-1, orderAmount:100
customerId:2, orderId:2-1, orderAmount: 125
customerId:1, orderId: 1-2, orderAmount: 112
............
}]


And I want to find the highest (or lowest) order per customer like

[{customerId:1, orderId:1-2, orderAmount:112},{.....}]


Is it possible to do either using any language construct (I am using Node.js) or lodash. I think can either sort by customerId or sort by orderAmount is straightforward in lodash but not the above combination

The only other way I can think of is double forEachOf (async) loop which may not be very efficient

Any help is appreciated....

Answer

Use orderBy with with order ascending or descending to decide if lowest or highest. Group by custormerId, and take the 1st item from each customer orders:

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>

Comments