【问题标题】:Remove duplicated values in a 2D array and return average values of all the keys values where the first key is duplicated删除二维数组中的重复值并返回第一个键重复的所有键值的平均值
【发布时间】:2013-12-03 22:42:31
【问题描述】:

我有一个 2D 数组,其中包含第一个键(时间)的重复值,我编写了一个 javascript :this is my try 删除重复值并返回第一次出现的频繁值,但我想做的正是, 是返回数组中每个剩余值的平均值: 例如这是我的输入

var testArray = [
  ['2011-08-01 20:46:04',10,40,20,20],//same time 
  ['2011-08-01 20:46:04',20,45,25,70], 

  ['2011-09-01 17:02:04',20,35,15,25],

  ['2012-10-01 16:55:44',30,30,10,30],//same time
  ['2012-10-01 16:55:44',40,45,13,23]

];

这是我想要的输出:

  var testArray = [
      ['2011-08-01 20:46:04',15,42.5,22.5,45],//save time only once and the resut of athors values is the average 

      ['2011-09-01 17:02:04',20,35,15,25],

      ['2012-10-01 16:55:44',35,37.5,11.5,26.5],

    ];

【问题讨论】:

    标签: javascript


    【解决方案1】:

    不是一个漂亮的代码,但我希望这会有所帮助!

    var testArray = [
            ['2011-08-01 20:46:04',10,40,20,20],//same time
            ['2011-08-01 20:46:04',20,45,25,70],
    
            ['2011-09-01 17:02:04',20,35,15,25],
    
            ['2012-10-01 16:55:44',30,30,10,30],//same time
            ['2012-10-01 16:55:44',40,45,13,23]
        ],
        dictionary = {}, result = [];
    
    testArray.forEach(function(element) {
        var time = element[0],
            currentValues = element.splice(1),
            storedValues;
    
        if(!dictionary[time]) {
            dictionary[time] = currentValues;
        }
    
        storedValues = dictionary[time];
    
        currentValues.forEach(function(currentElement, index) {
            storedValues[index] = (currentElement + storedValues[index]) / 2;
        })
    });
    
    for(var property in dictionary) {
        if(dictionary.hasOwnProperty(property)) {
            result.push([property].concat(dictionary[property]));
        }
    }
    
    console.log(result);
    

    这个输出:

    MacBookPro-do-Renato:stackoverflow Renato$ node so.js
    [ [ '2011-08-01 20:46:04', 15, 42.5, 22.5, 45 ],
      [ '2011-09-01 17:02:04', 20, 35, 15, 25 ],
      [ '2012-10-01 16:55:44', 35, 37.5, 11.5, 26.5 ] ]
    

    PS.: 此代码假定您在日期字符串之后始终具有相同数量的值

    【讨论】:

    • 此代码仍然有效。更改输入并自己检查,然后告诉您是否需要更详细的解释! :)
    • 问错了,因为这是有道理的
    猜你喜欢
    • 2017-08-27
    • 2018-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多