Entfernen Sie doppelte Werte in einem 2D -Array und geben Sie die Durchschnittswerte aller Schlüsselwerte zurück, bei denen der erste Schlüssel dupliziert wird

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

  •  25-08-2022
  •  | 
  •  

Frage

Ich habe ein 2D -Array, das doppelte Werte für den ersten Schlüssel (Zeit) enthält. Ich habe ein JavaScript geschrieben:Das ist mein Versuch Dadurch werden die doppelten Werte entfernt und das erste Auftreten eines häufigen Wertes zurückgegeben, aber ich möchte genau den Durchschnitt der einzelnen REST -Werte im Array zurückgeben: Zum Beispiel ist dies meine Eingabe

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]

];

Dies ist meine gewünschte Ausgabe:

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

    ];
War es hilfreich?

Lösung

Kein schöner Code, aber ich hoffe diese Hilfe!

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);

Dies gibt aus:

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 .: In diesem Code geht davon aus, dass Sie nach der Datumszeichenfolge immer die gleiche Anzahl von Werten haben werden

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top