How to count the number of elements in an array below/above a given number (JavaScript)


Consider we have an array of Numbers that looks like this −

const array = [3.1, 1, 2.2, 5.1, 6, 7.3, 2.1, 9];

We are required to write a function that counts how many of the elements are in the array below / above a given number.

For example, if the number is 5.25, the answer should be the following 5 elements,

(3.1, 1, 2.2, 5.1, 2.1)

and 3 elements above it −

(6, 7.3, 9)

Note − If any element is equal to the provided number, it should be counted as above the number.

So, let’s write the code for this function −

Example

const array = [3.1, 1, 2.2, 5.1, 6, 7.3, 2.1, 9];
const countNumbers = (arr, num) => {
   return arr.reduce((acc, val) => {
      const legend = ['upper', 'lower'];
      const isBelow = val < num;
      acc[legend[+isBelow]]++;
      return acc;
   }, {
      lower: 0,
      upper: 0
   });
};
console.log(countNumbers(array, 5.25));
console.log(countNumbers(array, 7));
console.log(countNumbers(array, 1));

Output

The output in the console will be −

{ lower: 5, upper: 3 }
{ lower: 6, upper: 2 }
{ lower: 0, upper: 8 }

Updated on: 26-Aug-2020

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements