We are required to write a function that counts how many of the elements are in the array below / above a given number.
Following is our array of Numbers −
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
For example, if the number is 60, the answer should be five elements below it −
54,54,43,3,23
and five element par it −
65,73,78,76,78
Example
Following is the code −
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
This will produce the following output in console −
{ below: 3, par: 9 } { below: 7, par: 5 } { below: 8, par: 4 }