hola no sabia como hacer esto
Digamos que tengo una matriz como esta
main = [ "1","2","A","4","5","B","6","7","A","8","9","B","10"];Quiero obtener una nueva matriz con resultado.
main2 = ["A","4","5","B","A","8","9","B"]y finalmente sepárelos de la siguiente manera;
main3 = ["A","4","5","B"] main4 = ["A","8","9","B"]Como puede ver, estoy sacando los elementos de la matriz de AB que ocurrieron dos veces.
Podría reducir la matriz en matrices, comenzando con un cierto valor y terminando con otro.
const start = 'A', end = 'B', data = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"], result = data.reduce((r, v) => { if (v === start) { r.push([v]); return r; } const last = r[r.length - 1]; if (last?.length && last[last.length - 1] !== end) last.push(v); return r; }, []); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }Otro enfoque
const start = 'A', end = 'B', data = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"], result = []; let i = data.indexOf(start); while (i !== -1) { let j = data.indexOf(end, i + 1); result.push(data.slice(i, ++j)); i = data.indexOf(start, j); } console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }Aquí está el enfoque de la vieja escuela.
const main = ["1", "2", "A", "4", "5", "B", "6", "7", "A", "8", "9", "B", "10"]; const start = "A"; const end = "B"; let result = []; let isCollecting = false; main.forEach(item => { if (item === start) isCollecting = true; if (isCollecting) result.push(item); if (item === end) { console.log(result); result = []; isCollecting = false; } });