
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
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
- Related Articles
- Form a sequence out of an array in JavaScript
- Checking if two arrays can form a sequence - JavaScript
- Can split array into consecutive subsequences in JavaScript
- Can form target array from source array JavaScript
- Check if the elements of the array can be rearranged to form a sequence of numbers or not in JavaScript
- Longest Consecutive Sequence in Python
- Determining whether numbers form additive sequence in JavaScript
- Length of the longest possible consecutive sequence of numbers in JavaScript
- Consecutive elements sum array in JavaScript
- JavaScript to check consecutive numbers in array?
- Compress array to group consecutive elements JavaScript
- Converting array into increasing sequence in JavaScript
- Binary Tree Longest Consecutive Sequence in C++
- Three strictly increasing numbers (consecutive or non-consecutive). in an array in JavaScript
- Finding Fibonacci sequence in an array using JavaScript

Advertisements