Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

147
Views
JS data transformation methods don't seem to be working

Create a function 'calcAverageHumanAge', which accepts an arrays of dog's ages ('ages'), and does the following things in order:

  1. Calculate the dog age in human years using the following formula: if the dog is <= 2 years old, humanAge = 2 * dogAge. If the dog is > 2 years old, humanAge = 16 + dogAge * 4
  2. Exclude all dogs that are less than 18 human years old (which is the same as keeping dogs that are at least 18 years old)
  3. Calculate the average human age of all adult dogs (you should already know from other challenges how we calculate averages )
  4. Run the function for both test datasets

Test data:

Data 1: [5, 2, 4, 1, 15, 8, 3] Data 2: [16, 6, 10, 5, 6, 1, 4]

My solution(idk why wont work):

const calcAverageHumanAge = function (ageList) {
const avgAge = ageList
.map(val => (val <= 2 ? 2 * val : 16 + val * 4))
.fliter(val => val >= 18)
.reduce((acc, val, i, list) => {
  return acc + val / list.length;
}, 0);};
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You have three issues. Your reduce doesn't return anything is the main problem, but you're also dividing by list.length in each callback which doesn't make any sense (actually it does and I'm dumb), and then you aren't returning anything from the function. You want something like this:

const calcAverageHumanAge = function (ageList) {
    const filteredVals = ageList
        .map(val => (val <= 2 ? 2 * val : 16 + val * 4))
        .filter(val => val >= 18);
    return filteredVals.reduce((acc, val) => acc + val) / filteredVals.length;
};

When run on your data:

calcAverageHumanAge([5, 2, 4, 1, 15, 8, 3]); // 44 
calcAverageHumanAge([16, 6, 10, 5, 6, 1, 4]); // 47.333
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!