tengo una matriz de objetos que tiene propiedades con valores booleanos y algunas propiedades con valores enteros. Por ejemplo
const arr = [{ _id: "621bb15de2ecadf024da51d3", draw: false, pixel: false, tooltip: 1, points: 1, }, { _id: "621bb15de2ecadf024da51d8", draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: "621bb15de2ecadf024da51da", draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: "621bb15de2ecadf024da51e5", draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: "621bb15de2ecadf024da51f8", draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: "621bb15ee2ecadf024da5222", draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: "621bb15ee2ecadf024da5230", draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: "621bb15fe2ecadf024da52f3", draw: false, pixel: false, tooltip: 1, points: 1, }, { _id: "621bb160e2ecadf024da5375", draw: false, pixel: true, tooltip: 0, points: 1, } ] Estoy tratando de lograr la suma de la información sobre tooltip y los points , también el recuento del draw y el pixel donde son verdaderos.
const res = arr.reduce(function ( acc, curr ) { return { tooltip: acc.tooltip + curr.tooltip, points: acc.points + curr.points, }; });Obtengo el resultado a continuación, que es correcto para sum,
{ points: 9, tooltip: 5 } pero también quiero contar el draw y el pixel donde su valor es verdadero.
Expected Result: { points: 9, tooltip: 5, pixel: 7, draw: 0 }Simplemente use la misma manera que lo hizo con la información sobre tooltip y point , ya que con el operador + entre 2 valores booleanos, estos valores booleanos se convertirán en enteros
const arr = [ { _id: '621bb15de2ecadf024da51d3', draw: false, pixel: false, tooltip: 1, points: 1, }, { _id: '621bb15de2ecadf024da51d8', draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: '621bb15de2ecadf024da51da', draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: '621bb15de2ecadf024da51e5', draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: '621bb15de2ecadf024da51f8', draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: '621bb15ee2ecadf024da5222', draw: false, pixel: true, tooltip: 0, points: 1, }, { _id: '621bb15ee2ecadf024da5230', draw: false, pixel: true, tooltip: 1, points: 1, }, { _id: '621bb15fe2ecadf024da52f3', draw: false, pixel: false, tooltip: 1, points: 1, }, { _id: '621bb160e2ecadf024da5375', draw: false, pixel: true, tooltip: 0, points: 1, }, ] const res = arr.reduce(function (acc, curr) { return { tooltip: acc.tooltip + curr.tooltip, points: acc.points + curr.points, draw: acc.draw + curr.draw, pixel: acc.pixel + curr.pixel, } }) console.log(res)Puedes probar esto:
let countPixel = 0; let countDraw = 0; const res = arr.reduce(function ( acc, curr ) { if (curr.pixel == true) { countPixel++; } if (curr.draw == true) { countDraw++; } return { tooltip: acc.tooltip + curr.tooltip, points: acc.points + curr.points, pixel: countPixel, draw: countDraw, }; });