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

詩: このコードは、日付文字列の後に常に同じ数の値を持っていると仮定しています

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top