I have a array of numbers. I want to print all values, but with interval if it's possible. For example:
[1,2,3,5,7,8,10]
I think you will understand what I want to get with example. For above array I want to get the following string:
"1-3, 5, 7-8, 10"
So, we have 1,2,3 in the array, then 5. The 4 is not present, so we close first interval and add to the string 1-3. Then continue, after 5 goes 7. In this case we can't create interval, therefore we just add 5. Then continue, we have 7, after 7 goes 8, after 8 goes 10, so we can create 7-8 interval only. the 10 is last so we just add it to string. In result, we have:
"1-3, 5, 7-8, 10".
I solved this task with the following:
let numbers = [1,2,3,4,7,9,12,13];
numbers.sort((a,b) => {return a - b});
let str='';
let startIndex =0, start, end;
if(numbers.length === 1) {
str = `${numbers[0]}`;
}
for(let i=0; i< numbers.length; i++) {
if(i === 0) {
continue;
}
if(numbers[i-1] +1 !== numbers[i]) {
start = numbers[startIndex];
end = numbers[i -1];
if(start - end === 0) {
str += `${start},`;
}
else {
str += `${start} - ${end},`;
}
startIndex = i;
}
if(i+1 === numbers.length) {
start = numbers[startIndex];
end = numbers[i];
if(start - end === 0) {
str += `${numbers[i]}`;
} else {
str += `${numbers[startIndex]} - ${numbers[i]}`;
}
}
}
console.log(str);
But, code looks very complex for understanding. Is there a better way to do this?