I am trying to find consecutive numbers from an array of numbers. This is my code:
let array = [4,3,5,4,3];
let new_arr = [];
for (let i=0; i<array.length; i++) {
let arr = [array[i]];
new_arr.push(arr);
if (array[i] - array[i+1] == 1) {
new_arr.push([array[i], array[i+1]]);
}
}
console.log(new_arr);
How do I get more than 2 elements in an array? In my example, [5,4,3]
should also be in the new_arr
. But I am only able to get 2 element arrays. What am I missing?
You need a nested loop. One possibility is, for each index after i
, in an inner loop, check if the following number is 1 less than the current. If so, create and push a new array - otherwise, break out and go to the outer loop's next iteration.
let inputArray = [4, 3, 5, 4, 3];
const allSequences = [];
for (let i = 0; i < inputArray.length; i++) {
let oneSequence = [inputArray[i]];
allSequences.push(oneSequence);
for (let j = i + 1; j < inputArray.length; j++) {
if (inputArray[j] === oneSequence[oneSequence.length - 1] - 1) {
oneSequence = [...oneSequence, inputArray[j]];
allSequences.push(oneSequence);
} else {
break;
}
}
}
console.log(allSequences);