Estoy buscando una forma limpia y eficiente de obtener el recuento de valor más alto mediante la suma de todos los atributos en la siguiente matriz json.
[{ "id":1, "material":2, "noMaterial":3, "negative":1 }, { "id":2, "material":4, "noMaterial":3, "negative":3}, { "id":3, "material":0, "noMaterial":1, "negative":1}]
Rendimiento esperado:
{ "noMaterial": 7 }
Esta no es la manera perfecta, pero puede ser de ayuda para usted.
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)Definí un enlace reutilizable que puede usar en otros atributos de su matriz de la siguiente manera:
function getSum(keyName, data) { return {[keyName]: data.reduce((acc, current) => { return acc + current[keyName]; }, 0) }; }y luego llame a aplicarlo en sus datos de la siguiente manera:
getSum("noMaterial", data);aquí hay un enlace para el código