Skip to content

Instantly share code, notes, and snippets.

@poeschko
Last active November 2, 2015 20:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save poeschko/18d47f567ed9432d0a32 to your computer and use it in GitHub Desktop.
Save poeschko/18d47f567ed9432d0a32 to your computer and use it in GitHub Desktop.
Count distinct items in an array
function countDistinct(items) {
var result = [];
for (var i = 0, l = items.length; i < l; ++i) {
var item = items[i];
var index = -1;
for (var j = 0; j < result.length; ++j) {
var existing = result[j];
if (item === existing[0]) {
index = j;
break;
}
}
if (index >= 0) {
++result[index][1];
} else {
result.push([item, 1]);
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment