Skip to content
Advertisement

Accumulate value by types in objects [closed]

I have an array containing objects for each object has a different type (wall type). I am trying to accumulate the total value for each area in order to check the total area for each wall:

const walls = [
  {
    typeName: "Sandwichelement - 480mm",
    area: 28.165,
  },
  {
    typeName: "Sandwichelement - 480mm",
    area: 22.165,
  },
  {
    typeName: "Beton vægelement - 150mm",
    area: 89.15,
  },
  {
    typeName: "Beton vægelement - 150mm",
    area: 165,
  },
  {
    typeName: "Fundament - 900mm",
    area: 45.2,
  },
  {
    typeName: "Fundament - 900mm",
    area: 16.5,
  },
];

const result = walls.reduce((acc, val) => {
  acc[val.typeName] = { totalArea: 0 };

  acc[val.typeName]["totalArea"] += val.area;

//the result:
//{
//"Beton vægelement - 150mm": {totalArea: 254.15},
//"Fundament - 900mm": {totalArea: 61.7},
//"Sandwichelement - 480mm": {totalArea: 50.33}
//}

  return acc;
}, {});

console.log(result);

Advertisement

Answer

Iterate through it and update a result object:

const result = {};

for (const {typeName, area} of walls) {
    if (!result[typeName]) {
        result[typeName] = {totalArea: 0};
    }

    result[typeName].totalArea += area;
}

console.log(result);
/*
{
"Beton vægelement - 150mm": {totalArea: 254.15},
"Fundament - 900mm": {totalArea: 61.7},
"Sandwichelement - 480mm": {totalArea: 50.33}
}
*/

const walls = [
  {
    typeName: "Sandwichelement - 480mm",
    area: 28.165,
  },
  {
    typeName: "Sandwichelement - 480mm",
    area: 22.165,
  },
  {
    typeName: "Beton vægelement - 150mm",
    area: 89.15,
  },
  {
    typeName: "Beton vægelement - 150mm",
    area: 165,
  },
  {
    typeName: "Fundament - 900mm",
    area: 45.2,
  },
  {
    typeName: "Fundament - 900mm",
    area: 16.5,
  },
];

const result = {};

for (const {typeName, area} of walls) {
    if (!result[typeName]) {
        result[typeName] = {totalArea: 0};
    }

    result[typeName].totalArea += area;
}

console.log(result);
/*
{
"Beton vægelement - 150mm": {totalArea: 254.15},
"Fundament - 900mm": {totalArea: 61.7},
"Sandwichelement - 480mm": {totalArea: 50.33}
}
*/
Advertisement