For typescript, this function takes a sorted array of numbers and groups them into a single string.
function convertNumberArrayToRangeString(numbers: number[]): string {
const delimiter = '~';
return numbers
.reduce((accumulator: string, currentValue: number, index: number, array: number[]) => {
if (index > 0 && array[index - 1] + 1 !== currentValue) {
if (index > 2 && array[index - 1] - array[index - 2] === 1) {
accumulator += delimiter + array[index - 1].toString();
}
accumulator += ',' + currentValue.toString();
} else if (index === 0 || index === array.length - 1) { // first or last
if (array[index - 1] === currentValue - 1) {
accumulator += delimiter;
} else if (index > 0) {
accumulator += ',';
}
accumulator += currentValue.toString();
}
return accumulator;
}, '');
}
const list = [1, 2, 3, 6, 7, 8]; // sorted unique list
const groupedList = convertNumberArrayToRangeString(list);
console.log(groupedList);
Output> "1~3,6~8"
How to do thatsounds like I was begging for an answer.