- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 }
Advertisements