Suppose we have a sorted array of numbers like this where we can have consecutive numbers.
const arr = [1, 2, 3, 5, 7, 8, 9, 11];
We are required to write a JavaScript function that takes one such array.
Our function should form a sequence for this array. The sequence should be such that for all the consecutive elements of the array, we have to just write the starting and ending numbers replacing the numbers in between with a dash (-), and keeping all other numbers unchanged.
Therefore, for the above array, the output should look like −
const output = '1-3,5,7-9,11';
Example
The code for this will be −
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]) { 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));
Output
And the output in the console will be −
1-3,5,7-9,11