2016-08-11 6 views
0

に基づいてソート私はのような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を使用しています)またはlodashを使用することは可能ですか?私は、私は考えることができる唯一の他の方法は非常に効率的

どれでもないかもしれませんダブルforEachOf(非同期)ループであることができますはcustomerIdによって、またはソートorderAmountによってどちらかの並べ替えは、上記の組み合わせ

lodashに簡単ですが、ないと思います助けがありがたいです....

答えて

0

使用orderBy。グループ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>

+0

おかげで、これはあなたがstackoverする新しいユーザーとして:)歓迎している – Subu

+0

私の作品、[お読みください何誰かが私の質問に答えるとどうすればいいですか?](http://stackoverflow.com/help/someone-answers)短いガイド。 –

0

_.sortByは、並べ替えるフィールドの配列を指定することができます。あなたは使用することができます。

var output = _.sortBy(input, ['customerId', 'orderAmount']); 

あなたは各customerIdの最大&分を見つけることが容易になるように、また、グループ配列へのオブジェクトは、あなたがソート_.groupBy、その後を使用することができますしたい場合。

var output = _.mapValues(_.groupBy(input, 'customerId'), function(val) { 
    return _.sortBy(val, 'orderAmount'); 
}); 

これは次のような構造を生成します:order昇順でまたは最低または最高かどうかを決定するための降順で

{ 
    "1": [ 
    { customerId: 1, orderId: "1-2", orderAmount: 112 }, 
    { customerId: 1, orderId: "1-1", orderAmount: 100 } 
    ], 
    "2": [ 
    { customerId: 2, orderId: "2-1", orderAmount: 125 } 
    ] 
} 
関連する問題