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