I want to show the numbers that don't show in the array in ranges, the array contains numbers ranging from 1 to 128.
for example for the array [87,89,90,91,92,93,94,95,96,97,99]
I want to print 1-86, 88, 98, 100-128
I wrote a function that works only when there are no numbers in the middle of the first unused number and the last
function PrintPorts(ports) {
var portString = "";
var open = true;
let index = 1
for (; index < 129; index++) {
for (let j = 0; j < ports.length; j++) {
if (index == ports[j]) {
open = false;
break;
} else
open = true;
}
if (open) {
portString += index;
break;
}
}
for (; index < 129; index++) {
for (let j = 0; j < ports.length; j++) {
if (index == ports[j]) {
open = false;
break;
} else
open = true;
}
if (!open) {
portString += "-" + (index - 1) + ",";
}
}
if (index == 129 && open) portString += "-" + (index - 1);
return portString;
}
console.log(PrintPorts([87,89,90,91,92,93,94,95,96,97,99]));
this is the result 1-86,-88,-89,-90,-91,-92,-93,-94,-95,-96,-98,-128 for the example array
when what I need is 1-86, 88, 98, 100-128
any help is appreciated
ports.includes(index)orports.indexOf(index) != -1rather than writing your own loop.