'Finding highest count by sum up of an attribute in an Json array in javascript

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 }



Solution 1:[1]

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ibrahim Banat