Skip to content

Instantly share code, notes, and snippets.

@mapodev
Last active October 7, 2015 10:26
Show Gist options
  • Save mapodev/9b902da73d8c39324f24 to your computer and use it in GitHub Desktop.
Save mapodev/9b902da73d8c39324f24 to your computer and use it in GitHub Desktop.
getCoherentNumbers() - returns blocks of coherent numbers in an array
/**
* getCoherentNumbers([1,2,3,5,6,8,9,10])
*
* returns [[1,2,3], [5,6], [8,9,10]]
*
* Works only for increasing numbers, like 1 2 3 4, not 5,1,3,2,4
*/
var getCoherentNumbers = function getCoherentNumbers(arr) {
var result = [];
var tmpArray = [];
for(var i = 0, l = Math.max.apply(null, arr); i < l; i++) {
if(typeof arr[i] != "undefined" && typeof arr[i + 1] != "undefined") {
if (arr[i] == (arr[i + 1] - 1)) {
tmpArray.push(arr[i]);
} else {
tmpArray.push(arr[i]);
result.push(tmpArray);
tmpArray = [];
}
} else if(typeof arr[i] != "undefined" && typeof arr[i + 1] == "undefined") {
if (arr[i - 1] == (arr[i] - 1)) {
tmpArray.push(arr[i]);
result.push(tmpArray);
} else {
if(typeof arr[i] != 'undefined') {
tmpArray.push(arr[i]);
}
result.push(tmpArray);
tmpArray = [];
}
}
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment