- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

- 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 ]

- Related Questions & Answers
- Average of first n even natural numbers?
- Print all increasing sequences of length k from first n natural numbers in C++
- Sum of square-sums of first n natural numbers
- Sum of first n natural numbers in C Program
- Sum of sum of first n natural numbers in C++
- Finding nth digit of natural numbers sequence in JavaScript
- Generating the sequence of first n look and say numbers in JavaScript
- Find the average of first N natural numbers in C++
- Finding sum of first n natural numbers in PL/SQL
- Sum of squares of first n natural numbers in C Program?
- C Program for cube sum of first n natural numbers?
- C++ Program for cube sum of first n natural numbers?
- Python Program for cube sum of first n natural numbers
- Java Program to cube sum of first n natural numbers
- Find the good permutation of first N natural numbers C++

Advertisements