Reputation: 63
I'm looking for clean and efficient way to get highest value count by sum up of all attributes in following json array.
[{ "id":1, "material":2, "noMaterial":3, "negative":1 }, { "id":2, "material":4, "noMaterial":3, "negative":3}, { "id":3, "material":0, "noMaterial":1, "negative":1}]
Expected Output:
{ "noMaterial": 7 }
Upvotes: 0
Views: 60
Reputation: 3480
This is not perfect way but may be it can be help to you.
var data = [{
"id": 1,
"material": 2,
"noMaterial": 3,
"negative": 1
}, {
"id": 2,
"material": 4,
"noMaterial": 3,
"negative": 3
}, {
"id": 3,
"material": 0,
"noMaterial": 1,
"negative": 1
}];
let keyName = ['material', 'noMaterial', 'negative'];
let [material, noMaterial, negative] = [0, 0, 0];
data.map((v,i)=>{
material += v.material;
noMaterial += v.noMaterial;
negative += v.negative;
});
const max = Math.max(material, noMaterial, negative);
const index = [material, noMaterial, negative].indexOf(max);
console.log(keyName[index]+':'+max)
Upvotes: 1
Reputation: 32
I defined a reusable hook that you can use on other attributes of your array as follows:
function getSum(keyName, data) {
return {[keyName]:
data.reduce((acc, current) => {
return acc + current[keyName];
}, 0)
};
}
and then call apply it on your data as follows:
getSum("noMaterial", data);
here is link for the code
Upvotes: 0