I have an array like this
var input = [
{
type: "A",
low: 1,
mid: 2,
high: 3,
},
{
type: "B",
low: 3,
mid: 2,
high: 0,
},
];
I want to do a function that help me collect all element in that array into a new array with only 2 element with the corresponding type, and the low, mid, high will be the total of them, i've tried the function below, and it works, but it look kind of silly.
let resultArr = [
{
category: "A",
low: 0,
mid: 0,
high: 0
},
{
category: "B",
low: 0,
mid: 0,
high: 0
}
]
input.forEach(element => {
if (element.type == "A") {
resultArr[0].low = element.low
resultArr[0].mid = element.high
resultArr[0].high = element.high
}
else {
resultArr[1].low = element.low
resultArr[1].mid = element.high
resultArr[1].high = element.high
}
});
console.log(resultArr)
Do we have another way to make it more "professional", thanks.
CodePudding user response:
You can reduce()
to an intermediate object, and then get its Object.values()
:
const data = [{
type: 'A',
low: 1,
mid: 2,
high: 3,
}, {
type: 'B',
low: 3,
mid: 2,
high: 0,
}];
const result = Object.values(data.reduce((a, {type, low, mid, high}) => {
a[type] = a[type] || {category: type, low: 0, mid: 0, high: 0};
a[type].low = low;
a[type].mid = mid;
a[type].high = high;
return a;
}, {}));
console.log(result);
CodePudding user response:
Maybe you are looking for a reduce
or groupBy
function.
Btw, it's clear and it works, man, why troubleing yourself and making it a little bit harder to maintain.
CodePudding user response:
var newInput = input.map(ele=> ({ type: ele.type, sum: ele.low ele.mid ele.high }));
This will solve the problem