cómo crear una nueva matriz con números acumulativos último índice al siguiente primer índice acumulativo.
tengo una matriz
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']La salida esperada será como
const newArray = [['3', '16'], ['19','31'], ['32','42'], ['43', '53'] ... ]Siempre hay al menos dos números acumulativos. Lo intenté
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)Un bucle forEach debería funcionar. Solo tienes que tener a mano el número previous para poder comparar.
Vea los comentarios dentro del código a continuación.
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);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) }consola.log(nuevoArray)
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']