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 because these numbers can be rearranged to form the consecutive sequence: 1, 2, 3, 4, 5.

Approach

To solve this problem, we need to:

  • Sort the array in ascending order
  • Check if each element is exactly one more than the previous element
  • Return true if all elements form a consecutive sequence, false otherwise

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

Testing with Different Arrays

Let's test our function with various arrays to see how it behaves:

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;
};

// Test cases
console.log("Array [3, 1, 4, 2, 5]:", canBeConsecutive([3, 1, 4, 2, 5]));
console.log("Array [1, 3, 5]:", canBeConsecutive([1, 3, 5]));
console.log("Array [10, 11, 12]:", canBeConsecutive([10, 11, 12]));
console.log("Array [1, 1, 2, 3]:", canBeConsecutive([1, 1, 2, 3]));
console.log("Empty array []:", canBeConsecutive([]));

Output

Array [3, 1, 4, 2, 5]: true
Array [1, 3, 5]: false
Array [10, 11, 12]: true
Array [1, 1, 2, 3]: false
Empty array []: false

How It Works

The function works by:

  1. First checking if the array is empty and returning false if so
  2. Creating a copy of the array to avoid modifying the original
  3. Sorting the copy in ascending order
  4. Iterating through the sorted array, comparing each element with the expected consecutive value
  5. If any element doesn't match the expected consecutive pattern, it returns false
  6. If all elements form a consecutive sequence, it returns true

Conclusion

This function efficiently determines if an array can form a consecutive sequence by sorting and checking each element. It handles edge cases like empty arrays and duplicate numbers correctly.

Updated on: 2026-03-15T23:19:00+05:30

189 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements