I'm currently trying to generate a new order of numbers from a current array with numbers from 1 - 10.
For example, I have arrary like this:
data = [
{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 6
},
{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 8
}
]
And i'm trying to generate a new order from this array from numbers from 1 - 10.
For example: I want it to generate a new order like this:
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 7 (The new number)
Where it checks the order of the array, and make a new order with numbers from 1 - 10
CodePudding user response:
First thing to do is to create an object with the total values. We can accomplish this by looping over each object in the array and add each value to a new object. For this we can use the reduce
method on the data
array.
After that loop over the object with the totals and divide each value with the amount of objects that are present in the data
array.
Use Math.round()
to round each value to the nearest whole number.
const data = [{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 6
},
{
0: 1,
1: 2,
2: 3,
3: 4,
4: 5,
5: 8
}
];
function getDataTotal(data) {
const totalObject = data.reduce((total, curObj) => {
for (const key of Object.keys(curObj)) {
total[key] = total[key]
? total[key] curObj[key]
: curObj[key];
}
return total;
}, {});
const averageObject = {};
for (const [key, value] of Object.entries(totalObject)) {
averageObject[key] = Math.round(value / data.length);
}
return averageObject;
}
const averageObject = getDataTotal(data);
console.log(averageObject);