Tag Archives: JavaScript

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:
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. 😉


Some new stuff for the blog

Due to a huge workload on my real-life job I was not very active on the TLB Project and did not write any blog posts.
I do not want to give up any of those things, especially not my job ;), so I decided to start posting some random css, html and javascript stuff on this blog.
I hope you will find those things useful and leave comments for those articles. 🙂