0

how to create new array with cumulative numbers last index to next cumulative first index.

I have an array-like

const numbers = [ '1',   '2',   '3',   '16',  '17',  '18',  '19',  '31',  '32', '42',  '43',  '53',  '54',  '58',  '59',  '69',  '70',  '81', '82',  '103', '104', '115', '116']

The expected output will be like

const newArray = [['3', '16'], ['19','31'], ['32','42'], ['43', '53'] ... ]

There is always at least two cumulative number. I tried

const numbers = ['1', '2', '3', '16', '17', '18', '19', '31', '32', '42', '43', '53', '54', '58', '59', '69', '70', '81', '82', '103', '104', '115', '116']

const reGroup = []

const findGroup = numbers.reduce((prev, current) => {
  data = []
  if (prev == (current - 1)) {
    data.push(prev, current)
  }
  reGroup.push(data)
})
console.log(reGroup)

2 Answers 2

3

A forEach loop should do. You just have to keep the previous number on hand for comparison.

See comments within the code below.

const numbers = [ '1', '2', '3', '16', '17', '18', '19', '31', '32', '42', '43', '53', '54', '58', '59', '69', '70', '81', '82', '103', '104', '115', '116']

let previous = 0;
let result = [];

// Loop though each array item
numbers.forEach(number => {
  // Have it as a number
  number = parseInt(number);

  // If the previous number + 1 does not equal this one
  if (previous + 1 != number) {
    // Push a sub array containing the previous number and this one (to string)
    result[result.length] = [previous.toString(), number.toString()];
  }

  // Save the current number for the next iteration
  previous = number;
});

/* The expected output will be like
        [['3', '16'], ['19','31'], ['32','42'], ['43', '53'] ... ]
    */
console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

0
const numbers = ['1', '2', '3', '16', '17', '18', '19', '31', '32', '42', '43', '53', '54', '58', '59', '69', '70', '81', '82', '103', '104', '115', '116']
let newArray = []
for(i=0; i < numbers.length; i+=2){
   const element = numbers.slice(0 + i, i +2)
   newArray.push(element)
}

console.log(newArray)

0: (2) ['1', '2']

1: (2) ['3', '16']

2: (2) ['17', '18']

3: (2) ['19', '31']

4: (2) ['32', '42']

5: (2) ['43', '53']

6: (2) ['54', '58']

7: (2) ['59', '69']

8: (2) ['70', '81']

9: (2) ['82', '103']

10: (2) ['104', '115']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.