Open In App

How many numbers in the given array are less/equal to the given value using the percentile formula ?

The following approach covers how to calculate how many numbers in the given array are less or equal to the given value using the percentile formula in JavaScript.

Problem Statement: You are given an array containing different integer values and also an integer value. You need to see how many numbers in the given array are less or equal to the given integer value and return the percentile value of the result using the percentile formula in JavaScript.



As an example take the array which is [1,2,3,4,5,6] and the given integer value is 6. So if we count how many elements are there which are less than and equal to 6 then we will see that there are 6 elements (1,2,3,4,5,6) that are less than and equal to 6. 

Therefore, according to the percentage formula, we will print our result as 100 percent since all the elements are less than and equal to the given integer value. There are several approaches to solving this particular problem. We have covered the following two approaches:



Approach 1:

Example: In this example, we will be using the Javascript for-in loop to check how many numbers are less than or equal to a given number.




<script>
    const percentileCalculation = (arr, val) => {
      let result = 0;
     
      for (let i in arr) {
        result = result + (arr[i] < val ? 1 : 0) +
        (arr[i] === val ? 0.5 : 0);
      }
     
      let resultDisplay = (result / arr.length) * 100;
      console.log(resultDisplay);
    };
     
    // Function call
    percentileCalculation([1, 2, 3, 4, 5, 6], 5);
</script>

Output:

75

Approach 2:

Example: In this example, we will be using the Javascript reduce() method to check how many numbers are less than or equal to a given number.




<script>
    const percentileCalculation = (arr, val) =>
      (100 *
        arr.reduce(
          (acc, v) => acc + (v < val ? 1 : 0) +
          (v === val ? 0.5 : 0),
          0
        )) /
      arr.length;
     
    // Function call
    console.log(percentileCalculation(
        [1, 2, 3, 4, 5, 6], 5));
</script>

Output:

75

Article Tags :