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

199
Views
How to return only numeric values?

I am trying to return the average. How can I get only the numbers and leave out false, "str"?

function average2 () {
    console.log (`arguments passed: ${arguments.length}`)
    console.log("All arguments:");
    let sum = 0;
    let numOnly = arguments.match(/\d+/)[0]
    for (let i= 0; i < arguments.length; i++) {
        sum += arguments[i]
    }
    return (sum) / arguments.length
}
console.log (average2 (5, 6, false, "str", 100))
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can filter numbers by using typeof operator, like this:

function average (...params) {
    const nums = params.filter(n => typeof n == 'number');
    return nums.reduce((acc,n) => acc+n) / nums.length;
}
console.log (average (5, 6, false, "str", 7))

in this example I just calculated average of nums, if you want to calculate average based on arguments length, you can replace return nums.reduce((acc,n) => acc+n) / nums.length; with return nums.reduce((acc,n) => acc+n) / params.length;

about 4 years ago · Juan Pablo Isaza Report

0

You can use this:

function average() {
    const numericArgs = [...arguments].filter(x => typeof x === 'number');
    return numericArgs.reduce((a, b) => a + b, 0) / numericArgs.length;
}

And you can use this:

function average(...args) {
    const numericArgs = args.filter(x => typeof x === 'number');
    return numericArgs.reduce((a, b) => a + b, 0) / numericArgs.length;
}
about 4 years ago · Juan Pablo Isaza Report

0

Just add a type check before doing the addition:

function average2 () {
    let sum = 0;
    for (let i= 0; i < arguments.length; i++) {
      if(typeof arguments[i] === "number"){
        sum += arguments[i]
      }
    }
    return (sum) / arguments.length
}
console.log (average2 (5, 6, false, "str", 100))

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!