Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Can array form consecutive sequence - 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
