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

307
Views
Javascript function that counts how many numbers are in the array (the array can contain other arrays)

How can I write a function that, received an array a already given from the program that can contain numbers, boolean and even other arrays, counts how many numbers are present in a?

Here's my code that doesn't work (it gives everytime 0 whatever the array contains):

function test(a) {
    var sum = 0
    for (i=0; i<a.length; i++){
       if (typeof a[i]==Number)
           sum++                    
    }
    return sum 
}

Thanks.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

you can try this:

const array = ["Hi", true, 10, "Car", 20, 50, 1500, false];
const flatedArray = array.flat(Infinity);
const count = flatedArray.filter(x => typeof x == 'number').length;
console.log(count) // 4

or change your code:

function test(a) {
    const flatedArray = a.flat(Infinity);
    let sum = 0
    for (i = 0; i < flatedArray.length; i++) {
        if (typeof a[i] == 'number') {
            sum++
        }
    }
    return sum
}

const array = ["Hi", true, 10, "Car", 20, 50, 1500, false];
console.log(test(array)) // 4

or change your function:

function test(a) {
    const flat = a.flat(Infinity);
    return a.filter(x => typeof x == 'number').length;
}

const array = ["Hi", true, 10, "Car", 20, 50, 1500, false];
console.log(test(array)) // 4
about 4 years ago · Juan Pablo Isaza Report

0

You have some issues:

  • typeof <operand> returns a string and not an object, you should be checking against a string typeof a[i] === "number".
  • You should be using var/let before i in your for loop so that i doesn't become a global variable and instead remains scoped to your function (if you use var) or your for loop (if you use let). Having variables accidentally added to the global scope can easily lead to bugs for code that runs after you call your test() function.

As you want to count the frequency of numbers in both your array and nested arrays, you can use recursion. The idea is to call your test() function again inside of test() when you encounter an array:

function test(a) {
  let sum = 0;
  for (let i = 0; i < a.length; i++) {
    if (typeof a[i] === "number")
      sum++
    else if(Array.isArray(a[i]))
      sum += test(a[i]); // sum the numbers within the `a[i]` array
  }
  return sum;
}

console.log(test([1,4, [2, 3, true], ["foo",0], 5, [123, [3.14, {a: 1}]]])); // 8

The other option is to get JS to handle the recursion for you, which can be done with the help of the .flat() method. By using .flat(Infinity) you can first flatten your array (ie: remove the inner arrays of any level), and then loop over it:

function test(a) {
  let sum = 0;
  let flat = a.flat(Infinity);
  for (let i = 0; i < flat.length; i++) {
    if (typeof flat[i] === "number")
      sum++;
  }
  return sum;
}

console.log(test([1,4, [2, 3, true], ["foo",0], 5, [123, [3.14, {a: 1}]]])); // 8

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!