Tag Archives: numberlist

Simplify an array of numbers to a string of numbers with ranges

The task i had was to simplify an array with a large list of numbers to a numberlist with ranges that is is shown with hyphens.

This is an example of numbers in an array:
1,3,41,7,12,17,13,14,22,23,24,25,55,26,27,30,38,39,40,42
and this is how the result should look like:
1, 3, 7, 12-14, 17, 22-27, 30, 38-42, 55

I thought this function might be pretty useful for others, so check it out.
The function expects an array of numbers, sorts the given numbers and will return a string of numbers.

function compressNumberList(numArray) {
	var str = '';
        numArray.sort(function(a,b){return a-b});
	for(var i = 0; i < numArray.length; i++) {
		var tmp;
		var hyphen = '-';
		tmp = numArray[i];
		var rest = numArray.length - i;
		var count = 0;
		for(var j = 1; j < rest; j++) {
			if(tmp+j == numArray[i+j]) {
				count = j;
			} 
		}
		var comma = ', ';
		if(numArray.length == i+1) {
			comma ='';
		}
		if(count > 0) {
			i = i +(count-1);
			comma = hyphen;
		}
		str += tmp + comma;
	}
	return str;
}

Of course, it's not very complicated, but i am sure it might save you some time 😉
Comments with a “translation” into other languages (e.g. python, c++, etc.) would be very welcome and helpful for others. 😉

zp8497586rq