
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Can Array Form Consecutive Sequence in JavaScript
We are required to write a JavaScript function that takes in an array of numbers and checks if the elements of the array can be rearranged to form a sequence of numbers or not.
For example −
If the array is −
const arr = [3, 1, 4, 2, 5];
Then the output should be −
true
Example
Following is the code −
const arr = [3, 1, 4, 2, 5]; const canBeConsecutive = (arr = []) => { if(!arr.length){ return false; }; const copy = arr.slice(); copy.sort((a, b) => a - b); for(let i = copy[0], j = 0; j < copy.length; i++, j++){ if(copy[j] === i){ continue; }; return false; }; return true; }; console.log(canBeConsecutive(arr));
Output
Following is the output in the console −
true
Advertisements