What is the best way to groupby objects in an array ?
For example, given this array of objects:
[
{ MachineName: "10020784 machineTypeA P.", Value: "5" },
{ MachineName: "80346 machineTypeA s", Value: "10" },
{ MachineName: "80349 machineTypeA k", Value: "15" },
{ MachineName: "80427 machineTypeA w", Value: "20" },
{ MachineName: "machineTypeX", Value: "25" },
{ MachineName: "machineTypeX", Value: "30" },
{ MachineName: "machineTypeX", Value: "35" },
{ MachineName: "machineTypeOther", Value: "40" }
{ MachineName: "machineTypeOther", Value: "40" }
]
What I’m looking for would be able to total specific values (if requested).
So if I did groupby MachineName, I’d want to receive:
[
{ MachineName: " machineTypeA .", Value: "50" },
{ MachineName: "machineTypeX", Value: "90" },
{ MachineName: "other", Value: "80" }
]
I currently use the Array.prototype.some() function :
Ausgabe = []
_.forEach(data, element => {
obj = {
MachineName: element.MachineName,
Value: element.Value,
}
Ausgabe.push(obj);
})
items1 = Ausgabe.filter(item => item.Anlage.indexOf('machineTypeA') !== -1);
items2 = Ausgabe.filter(item => item.Anlage.indexOf('machineTypeX') !== -1);
items3 = Ausgabe.filter(item => item.Anlage.indexOf('machineType') !== -1);
if (items1.length <= null){
}
else {
for (var i = 0; i < items1.length; i++){ // DZ
if (items1[i].Value <= null){
//count ++;
object1 = {
MachineName : 'machineTypeA',
}
} else {
if (items1[i].Value != null){
object1 = {
MachineName:'machineTypeA',
Value: items1[i].Value ,
}
}
}
}
Ausgabe2.push(object1)
}
if (items2.length <= null){
} else {
for (var i = 0; i < items2.length; i++){ // DZ
if (items2[i].Value <= 0){
//count ++;
object2 = {
MachineName : 'machineTypeX',
}
} else {
if (items1[i].MRT != null){
object2 = {
Value : 'machineTypeX',
MachineName : items2[i].Value ,
}
}
}
}
Ausgabe2.push(object2)
}
if(items3.length <= null){
}
else {
for (var i = 0; i < items3.length; i++){ // DZ
if (items3[i].Value <= 0){
//count ++;
object3 = {
MachineName : 'machineTypeOther',
}
} else {
if (items3[i].Value != null){
object3 = {
MachineName : 'machineTypeOther',
Value : items3[i].Value ,
}
}
}
}
Ausgabe2.push(object3)
}
The problem I have with this solution is that its fine for a small array ,
but for a larger arrays its ineffective because I would need to create x number of ‘items’.
If the MachineName would be equal I could use the following :
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
Is there a way to look for x amount of equal characters in a row and then group them accordingly ?