If I have an array [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7]
and you need to find each case of three consecutive numbers (regardless of whether it is ascending or descending), like I did it?
The second part would be to warn the array with the index of each of these sequences.
For example, the previous array will return [0,4,6,7]
.
So far I have it ... which is a rough start
var arr = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7]; var results = []; for (var i = 1; i < arr.length; i++) { if ((arr[i] - arr[i-1] != 1) && (arr[i] - arr[i+1] != 1)) { results.push(arr[i]); } } alert(results);
Thanks for the help!
Thanks for the math.abs pointer. This is what I ended up with:
var array = [1, 2, 3, 5, 10, 9, 8, 9, 10, 11, 7]; var indexes = []; for(var i=0; i < array.length; i++) { var diff = array[i+1] - array[i]; if(Math.abs(diff)==1 && array[i+1]+diff == array[i+2]) { indexes.push(i); } } alert(indexes);