Averaging between several arrays javascript

65 Views Asked by At

Hello everyone I’m stuck on an exercise I set myself.

I have several objects. Each of its objects contain an array that contain numbers related to the array index.

What I’m trying to do is to get, for example, an array that would return to me the average of each array’s index.

For example in my new table at index 0 I would have 4+7/2 , at index 1 I would have 5+6/2.

object1 = {
    "numbers": [{
            "number": 4,
        }, {
            "number": 5,
        }
    ]
}

object2 = {
    "numbers": [{

            "number": 7,
        }, {
            "number": 6,
        }
    ]
}

My first idea was to go on a reduce() but I did not success. Could you guide me? Thanks in advance. I would like to know if this is possible for several objects (object1 ,object2 , object3 ....) and also for more than two data in my tables "numbers"

2

There are 2 best solutions below

0
Alexander Nenashev On

You could use the numbers array's indexes to reduce all arrays:

const object1 = {
    "numbers": [{
            "number": 4,
        }, {
            "number": 5,
        }
    ]
},

object2 = {
    "numbers": [{

            "number": 7,
        }, {
            "number": 6,
        }
    ]
}

const source = [object1, object2]; // add extra objects here

const result = {numbers: [...source[0].numbers.keys()].map(i => 
  ({number: (source.reduce((r, obj) => r + obj.numbers[i].number, 0))/source.length}))};

console.log(result);

0
Selaka Nanayakkara On

Another alternative and efficient approach will be to calculate the averages. Instead of mapping over the transformed data twice, You can use a single loop to iterate through the objects and numbers to accumulate the sum and count for each index and then get the averages.

Refer the code below :

const object1 = {
    "numbers": [
        { "number": 4 },
        { "number": 5 }
    ]
};

const object2 = {
    "numbers": [
        { "number": 7 },
        { "number": 6 }
    ]
};

const objects = [object1, object2];

const numObjects = objects.length;
const numNumbers = objects[0].numbers.length;

const averages = Array.from({ length: numNumbers }, (_, index) => {
    let sum = 0;

    for (const obj of objects) {
        sum += obj.numbers[index].number;
    }

    return sum / numObjects;
});

console.log(averages);