Estoy tratando de separar una gran variedad en orden de jornada . Son 38 jornadas en total, intento mostrar los partidos por jornadas.
tengo esto
data.matches = [{matchday: 1, team: xxx}, {matchday: 1, team: xxx}, {matchday: 2, team: xxx} etc..]me gustaria algo asi
data.matches = [[{matchday: 1, team: xxx}, {matchday: 1, team: xxx} ],[{matchday: 2, team: xxx}] etc..]Para que pueda ver, creo una nueva matriz para cada día de partido diferente , esas nuevas matrices se anidarán dentro de la matriz principal.
Mi pobre intento:
let results: any = []; if (isSuccess) { data.matches.map((item: any) => { for (let i = 1; i < 38; i++) { if (item.matchday === i) { results.push(item); } else { results.splice(i, 0, item); } } }); console.log(results); }Puedes usar un reductor para eso. Reduzca a objeto con claves de jornadas y recupere sus valores. Algo como:
const matches = [ {matchday: 1, team: `yxx`}, {matchday: 1, team: `xyx`}, {matchday: 2, team: `xxy`}, {matchday: 15, team: `yyx`}, {matchday: 15, team: `yyy`} ]; const byDay = Object.values( matches.reduce( (acc, res) => { acc[`day${res.matchday}`] = acc[`day${res.matchday}`] ? acc[`day${res.matchday}`].concat(res) : [res]; return acc;}, {} ) ); console.log(byDay); .as-console-wrapper { max-height: 100% !important; }Puedes usar este método:
const matches = [{matchday: 1, team: "xxx"}, {matchday: 1, team: "xxx"}, {matchday: 2, team: "xxx"}] const result = Array.from(matches .reduce((m, val) => m.set(val.matchday, [...(m.get(val.matchday) || []), val]), new Map) .values() ); console.log(result)