Remove duplicated values in a 2D array and return average values of all the keys values where the first key is duplicated

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

  •  25-08-2022
  •  | 
  •  

Question

I have a 2D array that contains duplicated values for the first key (time),I wrote a javascript :this is my try that remove the duplicated values and return the first occurence of a frequent value, but what I want to do exactly, is to return the average of each of the rest values in the array: for example this is my input

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]

];

This is my desired output:

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

    ];
Was it helpful?

Solution

Not a beautiful code, but I hope this help!

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

This outputs:

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.: This code assumes that you will always have same number of values after the date string

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top