I need to create a function in javascript to show how many members of array are less than a given number

I think that my error is in the return section

I’ve tried many things but I can’t find the solution

the question is : “Write a function called countNums that gets two arguments – an array of numbers and some member And prints to the screen some organs in an array that are smaller than the given organ. For the screen, countNums([7,3,9,1,20], 10) will be printed to read: for example “4 elements are less than 10.”

function countNums(arr, element) {
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] < element) {
            return " " + arr[i] + "elements are less than" + element + " ";
        }
    }

}
arr = [14, 25, 36, 50]

document.write(countNums(arr, 20));

Answer

Javascript has functions that can help you do this easily, such as array.filter which will return a subset of an array depending upon the condition.

However, I’ve presented an answer that uses the logic you outlined in your own attempt but modified in order to return the correct result.

The primary problem with your code was that you were not actually counting the number of elements below the target number – instead you returned when the first array element was below the target number.

I’ve fixed that by adding a count variable to keep a running count.

In the if statement, if the array element is lower than the number then count is incremented by one. At the end of the function, the total running count is returned.

Here’s a working snippet showing this:

function countNums(arr, element) 
{
  let count = 0;

  for (var i = 0; i < arr.length; i++) {
    if (arr[i] < element) 
      count++;
  }
  
  return count;
}

let arr = [14,25,36,50] 
let num = 20;
let result = countNums(arr, num);
document.write(result + " element(s) are less than " + num);

In the snippet above, you can modify num to specify the target number that the array elements must be lower than. The output statement will be modified automatically to show the correct wording.