Tell us what’s happening:
Hi everyone, so, i have this code that i need to change to a ternary operator:
const getMode = (array) => {
const counts = {};
array.forEach(el => {
if (counts[el]) {
counts[el] += 1;
} else {
counts[el] = 1;
}
});
return counts;
}
I did it in two different ways, both showing errors:
array.forEach(el => counts [el] ? counts [el] += 1 : counts[el] = 1;
the other:
array.forEach(el => (counts[el] = counts[el] || 0) + 1);
I tnk i understood what is asked but im stuck lol.
Your code so far
/* file: script.js */
const getMean = (array) => array.reduce((acc, el) => acc + el, 0) / array.length;
const getMedian = (array) => {
const sorted = array.sort((a, b) => a - b);
const median =
array.length % 2 === 0
? getMean([sorted[array.length / 2], sorted[array.length / 2 - 1]])
: sorted[Math.floor(array.length / 2)];
return median;
}
// User Editable Region
const getMode = (array) => {
const counts = {};
array.forEach(el => counts[el] = (counts[el] || 0) + 1
});
return counts;
}
// User Editable Region
const calculate = () => {
const value = document.querySelector("#numbers").value;
const array = value.split(/,\s*/g);
const numbers = array.map(el => Number(el)).filter(el => !isNaN(el));
const mean = getMean(numbers);
const median = getMedian(numbers);
console.log(getMode(numbers));
document.querySelector("#mean").textContent = mean;
document.querySelector("#median").textContent = median;
}
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/134.0.0.0 Safari/537.36
Challenge Information:
Learn Advanced Array Methods by Building a Statistics Calculator - Step 35