I am trying to filter through a given array and only output the average of a new array's numbers. However, for some reason, the length of an array is based on the original array's length where other data types are located, although I specified the length to be based on a newArr array.
Could someone please help?
const bills = [[], 4, 42, 9, "error"];
const calcAverage = function (arr) {
let sum = 0;
let avg;
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === "number") {
sum = sum + arr[i];
avg = sum / arr.length
} else {
const newArr = arr.filter(arr => typeof arr[i] === "number");
for (let b = 0; b < newArr.length; b++) {
sum = sum + newArr[b];
avg = sum / newArr.length;
}
}
}
return avg;
}
console.log(calcAverage(bills));
You don't really need to use .filter with the for loop.
Instead you can keep a count of the amount of numbers encountered so far and use that to calculate your average. If you come across an item that isn't a number we can just skip it and move on.
const bills = [[], 4, 42, 9, 'error'];
const calcAverage = function (arr) {
let sum = 0, avg = 0;
for (let i = 0, count = 0; i < arr.length; i++) {
if (typeof arr[i] === 'number') {
count++;
sum += arr[i];
avg = sum / count;
}
}
return avg;
};
console.log(calcAverage(bills));
revised:
const bills = [[], 4, 42, 9, "error"];
const calcAverageOLD = function(arr) {
let sum = 0;
let avg;
// filter Before loop for correct length
const newArr = arr.filter(primitive => typeof(primitive) === "number");
console.log(newArr)
for (let i = 0; i < newArr.length; i++) {
sum += newArr[i];
avg = sum / newArr.length;
}
return avg;
}
console.log('old', calcAverageOLD(bills))
Are you trying to calculate the average from the numbers in the array?
I am not sure if I understand your question but here is what I did: First filter the numbers and then it's much easier to calculate the average
const bills = [[], 4, 42, 9, "error"];
const calcAvarage2 = function (arr){
let newArr = arr.filter( item=>typeof(item)==="number")
let sum = 0;
for( number of newArr){
sum += number;
}
let avg = sum/ newArr.length
return avg
}
console.log(calcAvarage2(bills));