我有这些数据:
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]
];
预期的输出应该是这样的:
var data = [
["School", 3,0,0],
["Warehouse", 0,3,0],
["Residential", 341, 532, 257],
["Gas Station", 0,1,0]
];
为了表示,
结果应该有这个序列:
建筑类型,1级计数,2级计数,3级计数
如果数组具有相同的级别和相同的建筑类型,则应添加计数值。
如何使用JavaScript或JQuery实现这一目标?
答案 0 :(得分:0)
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 );