我有3个数组,分别称为A,B和C。A和B是字符串数组,C是对象数组。
A = ['Geography1', 'Geography2', 'Geography3', ...];//length will range from 100 to 500.
B = ['Jan 2018', 'Feb 2018', 'Mar 2018' ...];//length will range from 12 to 36.
C = [
{"geoName": "Geography1", "month": "Jan 2018", "sales": 1, "growth": 12.11, "marketShare": 13.11},
{"geoName": "Geography1", "month": "Feb 2018", "sales": 2, "growth": 22.22, "marketShare": 23.22},
....
....
....
{"geoName": "Geography2", "month": "Jan 2018", "sales": 3, "growth": 33.33, "marketShare": 12.4},
{"geoName": "Geography2", "month": "Feb 2018", "sales": 4, "growth": 23.45, "marketShare": 12.4},
....
....
....
....
]; length will be A.length * B.length, approximately it will range from 1,200 to 18,000.
使用这些数组,并基于“销售”或“增长”,我需要生成另一个数组,例如D,它必须具有以下格式(显示的值是“销售”的值,如果我们按增长,增长过滤)值需要在每个地理位置\每月再次显示),使用for或for每个循环:
D = [
{"geoName":"Geography1", "Jan 2018": 1, "Feb 2018":2,....},
{"geoName":"Geography2", "Jan 2018": 3, "Feb 2018":4,....},
....
...
....
];
当前,这就是我的代码的样子,但是对于大型数据集而言,效率不高。执行需要很长时间:
function formatData(){
D = [];
var displayBy = "sales"; //or "growth"
for each(geoDesc in A)
{
var row = {};
row['geoName']= geoDesc;
var val:Number;
for each(var month:String in B)
{
val = getValue(C, month, geoDesc, displayBy)
row[month] = val;
}
D.push(row);
}
//D here will have final output
}
function getValue(source:Array, month:String, geoDesc:String,displayBy:String):Number
{
var value:Number = 0;
var len:int = source.length;
for(var i:int = 0; i < len; i++)
{
var item:Object = source[i];
if(item['month'] == month && item['geoName'] == geoDesc)
{
value = item[displayBy];
break;
}
}
return value;
}