xxxxxxxxxx
// calculate the average value for binary tree
const AvgValue = (root) => {
let result = [];
let avg = 0;
let sum = 0;
let queue = [root];
while (queue.length) {
let current = queue.shift();
result.push(current.data);
if (current.left) queue.push(current.left);
if (current.right) queue.push(current.right);
}
for (let i = 0; i < result.length; i++) {
sum = sum + result[i];
}
avg = Math.floor(sum / result.length);
return avg;
};
xxxxxxxxxx
const average = (args) => args.reduce((a, b) => a + b) / args.length;
average(1, 2, 3, 4);
// Result: 2.5
xxxxxxxxxx
const arr = [2, 4, 5, 6];
// Find average function
function fAve(totalVal, arrVal, index, array) {
const val = totalVal + arrVal;
if (index === array.lengh -1) {
return val / array.length;
}
return val;
}
// Pass function into reduce method
const average = arr.reduce(fAve);
console.log(average);
//node (js file name).