我的数据数组是
array = [{id: 2, name: "kent", status_id: 2, date_1: "2018-08-09", date_2: "2018-07-06"},{id: 2, name: "kent", status_id: 10, date_1: "2018-01-09", date_2: "2018-09-06"},{id: 3, name: "tracy", status_id: 2, date_1: "2018-05-03", date_2: "2018-10-02"},{id: 3, name: "tracy", status_id: 2, date_1: "2018-01-10", date_2: "2018-09-12"},{id: 3, name: "tracy", status_id: 10, date_1: "2018-02-10", date_2: "2018-09-02"},{id: 4, name: "lucy", status_id: 10, date_1: "2018-12-10", date_2: "2018-08-09"},{id: 5, name: "steve", status_id: 10, date_1: "2018-12-7", date_2: "2018-04-01"}]
如果id = 2,我想为每个id = 2找到max(date_1)和min(date_2)。就像我的输出一样,
id
2 max(date_1) min(date_2)
3 max(date_1) min(date_2)
4 max(date_1) min(date_2)
5 max(date_1) min(date_2)
我正在使用Lodash库。我会很感激的。
答案 0 :(得分:0)
您可以首先使用groupBy
mapValues
id ,然后映射每个分组的值,因为这将是一个对象。在映射分组值时,您可以使用_.maxBy
和_minBy
查找 max和min
var array = [{"id":2,"name":"kent","status_id":2,"date_1":"2018-08-09","date_2":"2018-07-06"},{"id":2,"name":"kent","status_id":10,"date_1":"2018-01-09","date_2":"2018-09-06"},{"id":3,"name":"tracy","status_id":2,"date_1":"2018-05-03","date_2":"2018-10-02"},{"id":3,"name":"tracy","status_id":2,"date_1":"2018-01-10","date_2":"2018-09-12"},{"id":3,"name":"tracy","status_id":10,"date_1":"2018-02-10","date_2":"2018-09-02"},{"id":4,"name":"lucy","status_id":10,"date_1":"2018-12-10","date_2":"2018-08-09"},{"id":5,"name":"steve","status_id":10,"date_1":"2018-12-7","date_2":"2018-04-01"}]
var res =
_(array)
.groupBy('id')
.mapValues(a => ({
max: _.maxBy(a, 'date_1').date_1,
min: _.minBy(a, 'date_2').date_2
})).value();
console.log(res);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>