- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Check if the elements of the array can be rearranged to form a sequence of numbers or not 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.
Therefore, let’s write the code for this function −
Example
The code for this will be −
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
The output in the console will be −
true
- Related Articles
- Program to check subarrays can be rearranged from arithmetic sequence or not in Python
- Check if a string can be rearranged to form special palindrome in Python
- Check if characters of a given string can be rearranged to form a palindrome in Python
- Can part of a string be rearranged to form another string in JavaScript
- C++ code to check array can be formed from Equal Not-Equal sequence or not
- C# Program to check whether the elements of a sequence satisfy a condition or not
- Check if all elements of the array are palindrome or not in Python
- Can array form consecutive sequence - JavaScript
- Check if elements of array can be made equal by multiplying given prime numbers in Python
- Check if elements of an array can be arranged satisfying the given condition in Python
- Program to check we can form array from pieces or not in Python
- Compute the sum of elements of an array which can be null or undefined JavaScript
- Form a sequence out of an array in JavaScript
- Find the count of sub-strings whose characters can be rearranged to form the given word in Python
- Checking if two arrays can form a sequence - JavaScript

Advertisements