Challenge 10
Array Analyzer
by Jaron Mauk
JavaScript
function arrayAnalyzer() {
var arr = Array.prototype.slice.call(arguments)
var obj = {
odds: 0,
negatives: 0,
avg: 0,
median: 0
}
// This gets the odds and negatives
arr.forEach(function(num) {
if (Math.abs(num) % 2 === 1) obj.odds++
if (num < 0) obj.negatives++
})
// This gets the avg, by using reduce to add all the numbers up
obj.avg = Number((arr.reduce(function(a, b) {
return a + b
}) / arr.length).toFixed(2))
// This gets the median by first sorting the array
// then checking if its odd or even amount of numbers
arr = arr.sort(function(a, b) {
return a - b
})
if (arr.length % 2 === 1) {
obj.median = arr[(arr.length - 1) / 2]
} else {
obj.median = (arr[arr.length / 2] + arr[(arr.length / 2) - 1]) / 2
}
return obj
}
arrayAnalyzer(7, -3, 0, 12, 44, -5, 3);