Matt Morales Matt Morales - 1 month ago 7
Javascript Question

Add values in Array based on other multiple values then regroup

I have this data:

var data = [
[1, "San Miguel National Central High School", "School", 1],
[1, "San Miguel Central Elementary School", "School", 2],
[2, "Medrano's Rice Mill and Warehouse", "Warehouse", 3],
[1, "Unknown", "Residential", 341],
[2, "Unknown", "Residential", 532],
[3, "Unknown", "Residential", 257],
[2, "Unknown", "Gas Station", 1]
];


And the intended ouput should be like this:

var data = [
["School", 3,0,0],
["Warehouse", 0,3,0],
["Residential", 341, 532, 257],
["Gas Station", 0,1,0]
];


For its representation,


  • data[i][0] --> Level

  • data[i][1] --> Building Name

  • data[i][2] --> Building Type

  • data[i][3] --> Count



The result should have this sequence:


Building Type, Level 1 Count, Level 2 Count, Level 3 Count


If the array has the same level and same building type the count value should be added.

How to achieve this using JavaScript or JQuery?

Answer

var input = [
  [1, "San Miguel National Central High School", "School", 1],
  [1, "San Miguel Central Elementary School", "School", 2],
  [2, "Medrano's Rice Mill and Warehouse", "Warehouse", 3],
  [1, "Unknown", "Residential", 341],
  [2, "Unknown", "Residential", 532],
  [3, "Unknown", "Residential", 257],
  [2, "Unknown", "Gas Station", 1]
];
    
var output = [];
    
function init() {
    var index = {};
    for (let building of input) {
        if (!index.hasOwnProperty(building[2])) {
            index[building[2]] = output.length;
            output.push([ building[2], 0, 0, 0 ]);
        }
        output[index[building[2]]][building[0]] += building[3];
    }
    console.log(output);
}
document.addEventListener( "DOMContentLoaded", init, false );

Comments