在工作中,我被赋予了以下任务:将数组中具有相似属性的元素分组。
通常,问题如下:
var order = [
{
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Speed"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Discharge pressure"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Speed"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"RCU",
"equipment":"37 P 552 B",
"parameter":"Discharge pressure"
}
]
如果我按“ ru”,“ area”,“ unit”,“ tot”,“ equipment”和“ parameter”对这些元素进行分组,则会得到以下结果:
var result = [
{
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"tot":2,
"equipment":"37 P 552 A",
"parameter":"Speed"
}, {
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"tot":1,
"equipment":"37 P 552 A",
"parameter":"Discharge Pressure"
}, {
"ru":"R401",
"area":"RFCC",
"unit":"RCU",
"tot":1,
"equipment":"37 P 552 B",
"parameter":"Discharge Pressure"
}];
经过一些实验,我来到了以下代码:
var groups = _.groupBy(order, function(value) {
return value.ru + "#" + value.area + "#" + value.unit + "#" + value.equipment + "#" + value.parameter + "#";
});
groups = _.map(groups, function(group) {
return _.extend(group[0], {tot: group.length});
});
现在我在如何对相似结果元素进行分组方面遇到问题。如果周围有人,请帮助我。预先感谢。
答案 0 :(得分:0)
如何?
var order = [
{
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Speed"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Discharge pressure"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Speed"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"RCU",
"equipment":"37 P 552 B",
"parameter":"Discharge pressure"
}
];
var result = [];
order.forEach(current=>{
let index = -1;
result.forEach((c,i)=>{
if (c.ru==current.ru && c.area==current.area && c.unit==current.unit && c.tot==current.tot && c.equipment==current.equipment && c.parameter==current.parameter){
index = i;
}
});
// console.log(index);
if(index==-1){
result.push(current);
}else{
result[index]["tot"] = result[index]["tot"]+current["tot"];
}
});
console.log(result);
答案 1 :(得分:0)
如果遇到类似的元素,也许可以避免分组并直接更新“索引”地图/对象中合并对象的tot
属性:
这是一个使用reduce
来实现的解决方案:
const order = [
{
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Speed"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Discharge pressure"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"OFFSITE",
"equipment":"37 P 552 A",
"parameter":"Speed"
}, {
"tot":1,
"ru":"R401",
"area":"RFCC",
"unit":"RCU",
"equipment":"37 P 552 B",
"parameter":"Discharge pressure"
}
]
const merged = Object.values(order.reduce((acc, curr) => {
const key = `${curr.ru}#${curr.area}#${curr.unit}#${curr.equipment}#${curr.parameter}`;
if (key in acc) acc[key].tot += 1;
else acc[key] = Object.assign({}, curr);
return acc;
}, {}));
console.log(merged);
console.log(merged.map(d => d.ru));