tengo una matriz como esta
var arr = ['2021-07-09T00:00:00Z','9242.80','4316.91','32557.90','14687.00','2021-07-10T00:00:00Z','9242.80','4316.91','32557.90','14687.00','2021-07-11T00:00:00Z','9242.80','4316.91','32557.90','14687.00','2021-07-12T00:00:00Z','9242.80','4316.91','32557.90','14687.00']Me gustaría hacer 4 matrices diferentes a partir de esta única matriz (ya sea por fecha o por orden de los elementos (por lo que, después de cada 5 elementos, se crea una nueva matriz). No he podido resolverlo incluso después de buscar. ¿Alguien podría indicarme la dirección correcta?
Puede usar reducir aquí para lograr el resultado deseado.
var arr = [ "2021-07-09T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", "2021-07-10T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", "2021-07-11T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", "2021-07-12T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", ]; const result = arr.reduce((acc, curr, i) => { if (i % 5 !== 0) acc[acc.length - 1].push(curr); else acc.push([curr]); return acc; }, []); console.log(result); /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }También puede generalizar la función como:
var arr = [ "2021-07-09T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", "2021-07-10T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", "2021-07-11T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", "2021-07-12T00:00:00Z", "9242.80", "4316.91", "32557.90", "14687.00", ]; function splitArrayAfter(arr, num) { return (result = arr.reduce((acc, curr, i) => { if (i % num !== 0) acc[acc.length - 1].push(curr); else acc.push([curr]); return acc; }, [])); } console.log(splitArrayAfter(arr, 5)); /* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */ .as-console-wrapper { max-height: 100% !important; top: 0; }Usando Array#reduce , puede iterar sobre la matriz. En cada iteración, agregamos una nueva matriz si recién estamos comenzando (es decir, no hay sub-matrices), el elemento es una fecha o hemos llegado a 5 elementos. De lo contrario, agregue el elemento al último subconjunto:
const arr = ['2021-07-09T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00', '2021-07-10T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00', '2021-07-11T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00', '2021-07-12T00:00:00Z', '9242.80', '4316.91', '32557.90', '14687.00']; const res = arr.reduce((list, e) => { if(Date.parse(e) || list.length === 0 || list[list.length-1].length === 5) { list.push([e]); } else { list[list.length-1].push(e); } return list; }, []); console.log(res);