0

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 }

3
  • 1
    What have you tried so far? Commented Feb 16, 2022 at 7:52
  • a for loop should do Commented Feb 16, 2022 at 7:54
  • You can use map() method like yourArray.map(v=>{ ... }). Commented Feb 16, 2022 at 9:11

2 Answers 2

1

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)

Sign up to request clarification or add additional context in comments.

1 Comment

I rewrite this code with more reliable so there is not need to write manually key name. check here...
0

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

2 Comments

sorry, I miss reading your question that you want the highest value.
output should be the key and value of highest count.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.