0

我编写了以下正常工作的代码,我正在创建一个新数组,该数组从数字中获取每两个成员并将它们相除。样本:

var numbers = [{ "name": "testvalue", "data": [10] }, 
               { "name": "testtotal", "data": [2]  }, 
               { "name": "prodvalue", "data": [10] }, 
               { "name": "prodtotal", "data": [2]  }];

var mydata = $.grep(numbers, function(e) {
    return new RegExp('^test*').test(e.name)
});

console.log(mydata) // prints [{"name": "testvalue", "data": [10]}, {"name": "testtotal", "data": [2]}]

result = [{
    "name": "testresult",
    "data": [mydata[0]["data"] / mydata[1]["data"]]
}];

console.log(result) // [{"name": "testresult", "data": [5]}]

我的问题是关于效率,我正在做的事情是高效的还是有更好的方法来做事?(我是 JS/jQuery 的新手,这就是我要问的原因)。

我不在乎数字的内容,我想要的只是每两个元素分开,每个元素名称都以总或值结尾

根据要求对真实数据进行采样。特别是数据来自graphite/d3.json

var data = 
[ {"target": "xs12t11.Busy",  "datapoints": [34,54,65,76,87] }, 
  {"target": "xs12t11.Total", "datapoints": [34,54,2,12,33]} ];
4

1 回答 1

0

我仍然不能完全确定我是否理解您的要求。我提供了两个迭代data并将其转换为结果的示例。

给定以下可能具有奇数行的输入:

var data = 
[ {"target": "xs12t11.Busy",  "datapoints": [34,54,65,76,87] }, 
  {"target": "xs12t11.Total", "datapoints": [34,54,2,12,33]  }, 
  {"target": "xs12t12.Busy",  "datapoints": [34,54,2,12,33]} ];

示例 1对每一行中的系列求和,并给出每对行有一个平均值的结果:

function sum(inArr) {
    var retVal = 0;

    for(var i = 0; i < inArr.length; ++i) retVal += inArr[i];
    return retVal;
}


var result = [];

// Increment by 2 to grab records in pairs
for(var i = 0; i < data.length; i += 2) {
    var series1 = data[i];
    var series2 = data[i+1];

    // Series1 always exists, but series2 may not
    if(!series2) break;

    result.push({
        name: series1.target.split('.')[0],
        data: sum(series1.datapoints)/sum(series2.datapoints)
    });
}

console.log(JSON.stringify(result));

输出

[{"name":"xs12t11","data":2.3407407407407406}]

示例 2返回具有一系列平均值的每对行的结果:

function avgSeries(series1, series2) {
    var retVal = [];
    var len = Math.min(series1.length, series2.length);

    for(var i = 0; i < len; i++) retVal.push(series1[i]/series2[i]);
    return retVal;
}

var result = [];

// Increment by 2 to grab records in pairs
for(var i = 0; i < data.length; i += 2) {
    var series1 = data[i];
    var series2 = data[i+1];

    // Series1 always exists, but series2 may not
    if(!series2) break;

    result.push({
        name: series1.target.split('.')[0],
        data: avgSeries(series1.datapoints, series2.datapoints)
    });
}

console.log(JSON.stringify(result));

输出

[{"name":"xs12t11","data":[1,1,32.5,6.333333333333333,2.6363636363636362]}]

如果这些都不符合您的目标,请告诉我。

于 2013-08-14T03:34:29.890 回答