Home > Net >  Find consecutive numbers when decreased by 1 in JavaScript
Find consecutive numbers when decreased by 1 in JavaScript

Time:08-22

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?

CodePudding user response:

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);

CodePudding user response:

Another option is to group consecutive numbers in sub arrays. Check inline comments:

// Numbers array
const arr = [4,3,5,4,3,7,2];

// New array
const new_arr = [];

// Sub array for consecutive group
let sub_arr = [];

// Loop
for(let i=0; i<arr.length; i  ) {
  // Push new digit to sub array
  sub_arr.push(arr[i]);
  
  // If next digit is not consecutive
  // push sub array to new array and
  // flush sub array
  if(arr[i] - arr[i 1] != 1) {
    new_arr.push(sub_arr);
    sub_arr = [];
  }
}

// Test
console.log(new_arr);

If you need only consecutive groups:

// Numbers array
const arr = [4,3,5,4,3,7,2];

// New array
const new_arr = [];

// Sub array for consecutive group
let sub_arr = [];

// Loop
for(let i=0; i<arr.length; i  ) {
  // Push new digit to sub array
  sub_arr.push(arr[i]);
  
  // If next digit is not consecutive
  // push sub array to new array and
  // flush sub array
  if(arr[i] - arr[i 1] != 1) {
    //
    // ONLY CONSECUTIVE GROUPS
    // Only push sub array to new array
    // if sub_arr has more then 2 elements
    //
    if(sub_arr.length > 1) new_arr.push(sub_arr);
    sub_arr = [];
  }
}

// Test
console.log(new_arr);

  • Related