Home > Mobile >  How to return only numeric values?
How to return only numeric values?

Time:01-03

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))

CodePudding user response:

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;

CodePudding user response:

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;
}

CodePudding user response:

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))

  • Related