At work, I was tasked with organizing elements in an array based on their similar properties.
The issue at hand is outlined as follows:
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"
}
]
If I group these elements by 'ru', 'area', 'unit', 'tot', 'equipment' and 'parameter', the result would be:
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"
}];
After some trial and error, I arrived at the following code snippet:
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});
});
I am now facing a challenge in grouping similar results. If anyone has any ideas or suggestions, please feel free to assist me. Thank you in advance.