Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Form a sequence out of an array in JavaScript
When working with sorted arrays containing consecutive numbers, we often need to represent sequences in a compressed format. Instead of listing all consecutive numbers, we can show ranges using a dash (-) separator.
For example, instead of [1, 2, 3, 5, 7, 8, 9, 11], we want to display "1-3,5,7-9,11".
Problem Statement
Given a sorted array of numbers, we need to:
- Group consecutive numbers into ranges (e.g., 1,2,3 becomes "1-3")
- Keep standalone numbers as-is
- Join all parts with commas
const arr = [1, 2, 3, 5, 7, 8, 9, 11]; // Expected output: "1-3,5,7-9,11"
Solution
Here's a function that builds a sequence string from a sorted array:
const arr = [1, 2, 3, 5, 7, 8, 9, 11];
const buildSequence = (arr = []) => {
let pointer;
return arr.reduce((acc, val, ind) => {
if (val + 1 === arr[ind + 1]) {
if (pointer == null) {
pointer = val;
}
return acc;
}
if (pointer) {
acc.push(`${pointer}-${val}`);
pointer = null;
return acc;
}
acc.push(val);
return acc;
}, []).join(',');
}
console.log(buildSequence(arr));
1-3,5,7-9,11
How It Works
The algorithm uses these key steps:
- Check for consecutive numbers: Compare current number with the next one
- Track sequence start: Use `pointer` to remember where a sequence began
- Build ranges: When a sequence ends, create "start-end" format
- Handle standalone numbers: Add individual numbers directly to the result
Alternative Approach
Here's a more readable version that processes the array in groups:
const buildSequenceReadable = (arr = []) => {
if (arr.length === 0) return '';
const result = [];
let start = arr[0];
let end = arr[0];
for (let i = 1; i < arr.length; i++) {
if (arr[i] === end + 1) {
end = arr[i]; // Extend the sequence
} else {
// Sequence broken, add to result
if (start === end) {
result.push(start.toString());
} else {
result.push(`${start}-${end}`);
}
start = arr[i];
end = arr[i];
}
}
// Add the last sequence
if (start === end) {
result.push(start.toString());
} else {
result.push(`${start}-${end}`);
}
return result.join(',');
}
const testArray = [1, 2, 3, 5, 7, 8, 9, 11, 15];
console.log(buildSequenceReadable(testArray));
1-3,5,7-9,11,15
Edge Cases
The function handles various edge cases properly:
// Empty array console.log(buildSequence([])); // Single element console.log(buildSequence([5])); // No consecutive numbers console.log(buildSequence([1, 3, 5, 7])); // All consecutive numbers console.log(buildSequence([1, 2, 3, 4, 5]));
5 1,3,5,7 1-5
Conclusion
This sequence builder efficiently compresses consecutive numbers into ranges using a dash separator. The algorithm processes the array once, making it O(n) time complexity, perfect for handling sorted numeric arrays.
