在2D数组中删除重复的值,并返回所有键值的平均值,其中第一个键是重复的

StackOverflow https://stackoverflow.com/questions/20353249

  •  25-08-2022
  •  | 
  •  

我有一个2D数组,其中包含第一个键(时间)的重复值,我写了一个JavaScript:这是我的尝试 删除重复的值并返回频繁值的第一个出现,但是我要确切地做的是返回数组中每个剩余值的平均值:例如,这是我的输入

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],

    ];
有帮助吗?

解决方案

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

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。: 该代码假设您将在日期字符串之后始终具有相同数量的值

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top