Been working on this challenge here. I know the code is probably overcomplicated. I think I’m on the right track. I just lose track of where the data is going… if that makes sense.
"Create a function called averageArray that takes in an array of numbers and a value of either ‘evens’ or ‘odds’ and, depending on which the function is asked to evaluate, returns either the average of all the even numbers in the array, or all of the odd numbers in the array. "
So, what I interpret from that is that I need to
- Create a new function called “averageArray”
- Said function needs two parameters, an array and a value of either evens or odds.
- Use a conditional statement to determine which set of code to execute. One for evens, one for odds.
- Filter this passed in array and create a new array with just the evens/odds
- Sum the evens/odds
- Divide the sum by the length of the input array
- return the average.
I’m curious as to whether I misunderstood the question, or if it was a coding error.
Here’s my code.
var arr1 = [15,17,22,4,3,35,11,12,38,8];
// Create a function that will average all the even or odd numbers in an array.
function averageArray(array, evensOrOdds){
var avg = 0; // return var declared
if (evensOrOdds === "evens") { //conditional set.
var evens = array.filter(num => num % 2 === 0); // % operator to sort that numbers
avg = (evens) => evens.reduce((a, b) => a + b) / evens.length;
return avg; // output sum
} else {
var odds = array.filter(num => num % 2 === 1);
avg = (odds) => odds.reduce((a, b) => a + b) / odds.length;
return avg;
}
}