- 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
Returning array of natural numbers between a range in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of two numbers [a, b] (a <= b), specifying a range.
Our function should return an array of all natural numbers between a and b including them
Example
Following is the code −
const range = [6, 45]; const naturalBetweenRange = ([lower, upper] = [1, 1]) => { if(lower > upper){ return []; }; const res = []; for(let i = lower; i <= upper; i++){ res.push(i); }; return res; }; console.log(naturalBetweenRange(range));
Output
[ 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45 ]
Advertisements