Group a sorted array based on the difference between current and previous elements in JavaScript

In JavaScript, grouping a sorted array based on the difference between consecutive elements is a common problem where we need to create separate groups whenever the difference exceeds a certain threshold (typically 1). This technique is useful for analyzing sequences and identifying continuous ranges in data.

Understanding the Problem

Given a sorted array, we need to group elements where consecutive elements have a difference of 1 or less. When the difference between current and previous elements exceeds 1, we start a new group. For example, the array [1, 2, 3, 5, 7, 9] should be grouped as [[1, 2, 3], [5], [7], [9]] since 1?2?3 are consecutive, but 3?5 has a difference of 2.

Algorithm Steps

Step 1: Initialize an empty result array and a current group with the first element.
Step 2: Iterate through the array starting from the second element.
Step 3: Calculate the difference between current and previous elements.
Step 4: If difference ? 1, add to current group; otherwise, save current group and start a new one.
Step 5: Add the final group to results.

Implementation

function groupByDifference(arr) {
   // Handle empty array
   if (arr.length === 0) {
      return [];
   }
   
   const result = [];
   let currentGroup = [arr[0]];
   
   // Iterate through array starting from second element
   for (let i = 1; i < arr.length; i++) {
      const difference = arr[i] - arr[i - 1];
      
      // If difference is 1 or less, add to current group
      if (difference <= 1) {
         currentGroup.push(arr[i]);
      } else {
         // Save current group and start new one
         result.push(currentGroup);
         currentGroup = [arr[i]];
      }
   }
   
   // Add the final group
   result.push(currentGroup);
   return result;
}

// Test with sample data
const sortedArray = [1, 2, 3, 5, 7, 9, 10, 14, 16, 17, 20, 21, 23];
const groupedArray = groupByDifference(sortedArray);

console.log("Original array:", sortedArray);
console.log("Grouped array:", groupedArray);
Original array: [
   1,  2,  3,  5,  7,  9,
  10, 14, 16, 17, 20, 21,
  23
]
Grouped array: [
  [ 1, 2, 3 ],
  [ 5 ],
  [ 7 ],
  [ 9, 10 ],
  [ 14 ],
  [ 16, 17 ],
  [ 20, 21 ],
  [ 23 ]
]

Alternative Approach with Custom Threshold

You can modify the function to accept a custom threshold for grouping:

function groupByCustomDifference(arr, threshold = 1) {
   if (arr.length === 0) return [];
   
   const result = [];
   let currentGroup = [arr[0]];
   
   for (let i = 1; i < arr.length; i++) {
      const difference = arr[i] - arr[i - 1];
      
      if (difference <= threshold) {
         currentGroup.push(arr[i]);
      } else {
         result.push(currentGroup);
         currentGroup = [arr[i]];
      }
   }
   
   result.push(currentGroup);
   return result;
}

// Test with different thresholds
const testArray = [1, 3, 4, 7, 8, 9, 15, 17];

console.log("Threshold 1:", groupByCustomDifference(testArray, 1));
console.log("Threshold 2:", groupByCustomDifference(testArray, 2));
Threshold 1: [ [ 1 ], [ 3, 4 ], [ 7, 8, 9 ], [ 15 ], [ 17 ] ]
Threshold 2: [ [ 1, 3, 4 ], [ 7, 8, 9 ], [ 15, 17 ] ]

Complexity Analysis

Complexity Value Explanation
Time O(n) Single pass through the array
Space O(n) Result array stores all elements

Common Use Cases

This grouping technique is useful for:

  • Finding consecutive number ranges in datasets
  • Analyzing time series data for continuous periods
  • Grouping related items based on incremental values
  • Processing sorted arrays for pattern recognition

Conclusion

Grouping sorted arrays by difference between consecutive elements is efficiently solved with a single-pass algorithm. The approach maintains linear time complexity while providing flexible threshold-based grouping for various data analysis scenarios.

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

539 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements