我有以下表格的数据。我正在逐行使用loadash for groupby。但是,loadash groupby是基于行值返回组,我期望它应该忽略行之间的1个值的小差异然后分组。恩。它应该在一个组中添加第9行和第10行的项目。我应该从groupby回调函数返回什么,它将通过包含相邻值来对属性进行分组。
[
{
"row": 9,
"city": "Camas"
},
{
"row": 9,
"city": "Kersey"
},
{
"row": 6,
"city": "Ebro"
},
{
"row": 10,
"city": "Orick"
},
{
"row": 2,
"city": "Bonanza"
},
{
"row": 6,
"city": "Rowe"
},
{
"row": 5,
"city": "Walland"
}
]
预期产出
{
2: [
{
"row": 2,
"city": "Bonanza"
},
],
5: [
{
"row": 6,
"city": "Ebro"
},
{
"row": 6,
"city": "Rowe"
},
{
"row": 5,
"city": "Walland"
}
],
9: [{
"row": 9,
"city": "Camas"
},
{
"row": 9,
"city": "Kersey"
},
{
"row": 10,
"city": "Orick"
}
]
}
答案 0 :(得分:1)
解决此问题的一种方法是sort按row
按升序排列,然后reduce排序集合,方法是将行差异合并为1并简单地指定那些没有的人。
var result = _(data)
.sortBy('row')
.reduce(function(group, item) {
var nIndex = item.row - 1;
var value = [item];
if (group[nIndex]) {
group[nIndex] = value.concat(group[nIndex]);
} else {
group[item.row] = value;
}
return group;
}, {});
var data = [{
"row": 9,
"city": "Camas"
},
{
"row": 9,
"city": "Kersey"
},
{
"row": 6,
"city": "Ebro"
},
{
"row": 10,
"city": "Orick"
},
{
"row": 2,
"city": "Bonanza"
},
{
"row": 6,
"city": "Rowe"
},
{
"row": 5,
"city": "Walland"
}
];
var result = _(data)
.sortBy('row')
.reduce(function(group, item) {
var nIndex = item.row - 1;
var value = [item];
if (group[nIndex]) {
group[nIndex] = value.concat(group[nIndex]);
} else {
group[item.row] = value;
}
return group;
}, {});
console.log(result);
body>div {
min-height: 100%;
top: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
上述解决方案也可以使用vanilla JS Array#sort和Array#reduce
来实现var result = data
.sort(function(v1, v2) {
return v1.row - v2.row;
})
.reduce(function(group, item) {
var nIndex = item.row - 1;
var value = [item];
if (group[nIndex]) {
group[nIndex] = value.concat(group[nIndex]);
} else {
group[item.row] = value;
}
return group;
}, {});
var data = [{
"row": 9,
"city": "Camas"
},
{
"row": 9,
"city": "Kersey"
},
{
"row": 6,
"city": "Ebro"
},
{
"row": 10,
"city": "Orick"
},
{
"row": 2,
"city": "Bonanza"
},
{
"row": 6,
"city": "Rowe"
},
{
"row": 5,
"city": "Walland"
}
];
var result = data
.sort(function(v1, v2) {
return v1.row - v2.row;
})
.reduce(function(group, item) {
var nIndex = item.row - 1;
var value = [item];
if (group[nIndex]) {
group[nIndex] = value.concat(group[nIndex]);
} else {
group[item.row] = value;
}
return group;
}, {});
console.log(result);
body>div {
min-height: 100%;
top: 0;
}