I've a task to write function that returns the average value of even numbers from an array. If there are no even numbers in the array, return null. Here are arrays and expected result: [1,2,3,4,5,6,7] - should return "4" and [1,1,1,1] - should return "null". Where shall I put condition for null?I've tried different options but nothing works but maybe my code is wrong.
function getEvenAverage(array) {
const even = array.filter(function (element) {
return element % 2 === 0
});
const sum = even.reduce(function (sum, element) {
return (sum + element);
});
return sum / even.length;
}
const result1 = getEvenAverage([1,2,3,4,5,6,7])
console.log(result1);
const result2 = getEvenAverage([1,1,1,1])
console.log(result2);
You can achieve this in 1 loop as well:
map) to hold valuesmapfunction getEvenAverage(array) {
const map = array.reduce((acc, item) => {
if (item % 2 === 0) {
return { total: acc.total + item, length: acc.length + 1 }
}
return acc
}, { total: 0, length: 0 });
return map.length ? map.total / map.length : null
}
const result1 = getEvenAverage([1, 2, 3, 4, 5, 6, 7])
console.log(result1);
const result2 = getEvenAverage([1, 1, 1, 1])
console.log(result2);
check this code
function getEvenAverage (arr) {
let temp = [];
let sum = 0;
let count = 0;
arr.map(item => {
if(item % 2 === 0) {
temp = [...temp, item]
}
})
temp.map(item => {
sum += item;
count +=1;
})
if(temp.length ===0) {
return null
}
return sum/count;
}
You need to do the following changes:
null as an initial value for Array.prototype.reducesum === null return sum, otherwise calculate an average valueYou can find the code with changed applied below
function getEvenAverage(array) {
const even = array.filter(function (element) {
return element % 2 === 0
});
const sum = even.reduce(function (sum, element) {
return (sum + element);
}, null);
return sum === null ? sum : sum / even.length;
}
const result1 = getEvenAverage([1,2,3,4,5,6,7])
console.log(result1);
const result2 = getEvenAverage([1,1,1,1])
console.log(result2);