Upper or lower elements count in an array in JavaScript



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

const array = [54,54,65,73,43,78,54,54,76,3,23,78];

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 60 −

The answer should be 5 elements below it (54,54,43,3,23) and 5 element par it (65,73,78,76,78) Therefore, let’s write the code for this function −

Example

The code for this will be −

const array = [54,54,65,73,43,78,54,54,76,3,23,78]; const belowParNumbers = (arr, num) => {    return arr.reduce((acc, val) => {       const legend = ['par', 'below'];       const isBelow = val < num;       acc[legend[+isBelow]]++;       return acc;    }, {       below: 0,       par: 0    }); }; console.log(belowParNumbers(array, 50)); console.log(belowParNumbers(array, 60)); console.log(belowParNumbers(array, 70));

Output

The output in the console will be −

{ below: 3, par: 9 } { below: 7, par: 5 } { below: 8, par: 4 }
Updated on: 2020-10-20T11:37:33+05:30

125 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements