根据第二个数组中的值过滤和平均一个数组中的值

时间:2017-05-12 07:53:36

标签: javascript

我有两个独立的阵列:一个用于执行测量的小时,另一个用于在该小时获得的结果。示例:(实际数据更长)

function ave (a) {
        var total = 0;
        for(var i = 0; i <= a.length-1; i++) {
            total += a[i];
        }
        return total / a.length;    
    }

var unique = Array.from(new Set(hours));
unique.sort(function(a, b){return a-b});

var arr_res= [];
var build_arr =[];

for (var i = 0; i <= unique.length-1; i++) {
    build_arr.length = 0;
    for (var j = 0; j <= results-1; j++) {
        if (hours[j] == unique[i]) {
            build_arr.push(results[j]);
        }
    }
    arr_res.push(ave(build_arr));
} 

我对另一个进行策划,现在我需要找到每小时的平均值。起初我认为这是一件微不足道的事情,但它变得非常复杂。我打赌有一种简单的方法可以做到,我无法找到它。我搜索了几个有关它的相关问题,并在下面提出了解决方案。它有效,但速度很慢,肯定有办法做得更好。 (请注意,对于绘图,我需要以独特小时结束的排序数组和包含每小时平均值的等效排序数组)。

SELECT * 
FROM `table`
WHERE  CASE `type`
        WHEN  'a' THEN `category` IN ('CAT1','CAT2','CAT3') 
        WHEN 'b' THEN `category` IN  ('CAT4') 
        ELSE `category` IN ('undefined','n/a')
    END
ORDER BY `category`

3 个答案:

答案 0 :(得分:0)

您可以通过合并Array.map()Object.keys()var hours =[10,8,13,7,8,12,10,13,23,12]; var results =[101, 104, 101, 106, 101, 107, 109, 110, 112, 107]; var groups = hours.reduce(function(acc, hour, idx) { acc[hour] = acc[hour] || []; acc[hour].push(results[idx]); return acc; }, {}); //console.log(groups); var averages = Object.keys(groups).sort(function(a, b) { return a-b; }).map(function(key) { return groups[key].reduce(function(sum, val) { return sum+val; }) / groups[key].length; }); console.log(Object.keys(groups).sort(function(a, b){return a - b;})); console.log(averages);来实现这样的目标:

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx"
    args = [iter(iterable)] * n
    return zip_longest(*args, fillvalue=fillvalue)

答案 1 :(得分:0)

如果我正确理解了这个问题,那么以下内容应该有效:

以下输出为:

**

  

7-106,8-102.5,10-105,12-107,13-105.5,23-112

**

var hours = [10, 8, 13, 7, 8, 12, 10, 13, 23, 12];
var results = [101, 104, 101, 106, 101, 107, 109, 110, 112, 107];

function toObject(names, values) {
    var result = [];
    for (var i = 0; i < names.length; i++)
        result.push({ hour: names[i], result: values[i]});
    return result;
}

function average(arr) {
    var sums = {}, counts = {}, results = [], name;
    for (var i = 0; i < arr.length; i++) {
        name = arr[i].hour;
        if (!(name in sums)) {
            sums[name] = 0;
            counts[name] = 0;
        }
        sums[name] += arr[i].result;
        counts[name]++;
    }

    for(name in sums) {
        results.push({ name: name, value: sums[name] / counts[name] });
    }
    return results;
}

function Test() {

    var result = toObject(hours, results);
    var averagess = average(result);

    for (var i = 0; i < averagess.length; i++) {
        console.log(averagess[i].name + '-' + averagess[i].value);
    }
}

答案 2 :(得分:0)

1. Iterate over hours array
2. Create an object that would have at it's key the value of hour
3. The value would be the value from results array when you are adding the key first time.
4. When that same key is found subsequently, the average is computed and added as modified value.
5. Push the obj values into an array by iterating the object
6. Sort the array by hour. If this array is enough stop else collect the result in two arrays.

See the solution below:

&#13;
&#13;
var hours = [10, 8, 13, 7, 8, 12, 10, 13, 23, 12];

    var results = [101, 104, 101, 106, 101, 107, 109, 110, 112, 107];
    var obj = {};
    var avg = 0,
      tempCount;
    hours.forEach(function(v, i) {
      if (!obj[v]) {
        obj[v] = {
          hour: v,
          val: results[i],
          count: 1
        };
      } else {
        tempCount = obj[v].count + 1;
        avg = (obj[v].val + results[i]) / tempCount;
        obj[v] = {
          hour: v,
          val: avg,
          count: tempCount
        };
      }

    });
//You have got averages by now.                                              //Only thing remaining is to get the right output //data structures.


var res = [];
for (var i in obj) {
  if (obj.hasOwnProperty(i)) {
    //console.log("Key=" + i, "Val=" + obj[i].val);
    res.push(obj[i]);
  }
}
res = res.sort(function(a, b) {
  return a.hour - b.hour;
});
var hourRes = [],
    avgRes  = [];
res.forEach(function (v, i) {
  hourRes.push(v.hour);
  avgRes.push(v.val);
});

console.log(hourRes, avgRes);
&#13;
&#13;
&#13;