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

Updated on: 17-Oct-2020

106 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements