![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
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
Building a lexicographically increasing sequence of first n natural numbers in JavaScript
Problem
We are required to write a JavaScript function that takes in a number n and return an array containing first n natural number.
The only condition is that the numbers should be sorted lexicographically which means all the numbers starting with 1 should come before any starting with 2 or 3 or 4 and so on.
Example
Following is the code −
const num = 24; const buildLexicographically = (num = 1) => { const res = []; const curr = num >= 9 ? 9 : num; for (let i = 1; i <= curr; i++) { res.push(i); for (let j = i * 10; j<=num; j++) { res.push(j) if(j % 10 === 9){ break; } } }; return res; }; console.log(buildLexicographically(num));
Output
Following is the console output −
[ 1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 2, 20, 21, 22, 23, 24, 3, 4, 5, 6, 7, 8, 9 ]
Advertisements