I'm trying to think of a way to make this code simple, with the smallest amount of loops and variables, but I'm having trouble.
I want to get the average object in the array 'numbers', based on the 'value'. I feel that there must be a mathematical way to get the average without finding the closest average in another loop.
Currently I have this mess:
var numbers = [
{ value: 41 },
{ value: 19 },
{ value: 51 },
{ value: 31 },
{ value: 11 }
];
// Find average:
var sum = 0;
for (var i = 0; i < numbers.length; i++) {
sum += numbers[i].value;
}
var average = sum / numbers.length;
// Find closest object to average:
var match, difference;
for (var j = 0; j < numbers.length; j++) {
const diff = Math.abs(average - numbers[j].value);
if (difference === undefined || diff < difference) {
difference = diff;
match = numbers[j];
}
}
// Print junk:
console.log("AVERAGE NUMBER: " + average);
console.log("CLOSEST OBJECT: " + match);
console.log("CLOSEST NUMBER: " + match.value);
I need to retrieve the object because it contains other information that I need to use.
Any help would be highly appreciated!