tengo una matriz de
let arr = [ {workoutName : 'push-up'}, {workoutName : 'plank'}, {workoutName : 'single-Leg (Left)'}, {workoutName : 'arm-extend (Right)'}, {workoutName : 'Jumping Jack'}, {workoutName : 'single-Leg (Right)'}, {workoutName : 'something (Left)'}, {workoutName : 'arm-extend (Left)'}, {workoutName : 'somethingElse'}, {workoutName : 'something (Right)'} ]Me gustaría ordenar/cambiar los objetos originales para que coincidan con sus pares si están disponibles en esta lista y mantener el posicionamiento. Como cambiar los nombres sin romper la estructura actual.
Esto lo ordena, pero necesito mantener el mismo orden.
let sorted = arr.sort( function( a , b){ if(a.workoutName > b.workoutName) return 1; if(a.workoutName < b.workoutName) return -1; return 0; }); console.log(sorted); Array [ Object { workoutName: "Jumping Jack" }, Object { workoutName: "arm-extend (Right)" }, Object { workoutName: "arm-extend (Left)" }, Object { workoutName: "plank" }, Object { workoutName: "push-up" }, Object { workoutName: "single-Leg (Left)" }, Object { workoutName: "single-Leg (Right)" }, Object { workoutName: "something (Left)" }, Object { workoutName: "something (Right)" }, Object { workoutName: "somethingElse" } ]Resultado Esperado
[ {workoutName : 'push-up'}, {workoutName : 'plank'}, {workoutName : 'single-Leg (Left)'}, {workoutName : 'single-Leg (Right)'}, {workoutName : 'arm-extend (Right)'}, {workoutName : 'arm-extend (Left)'}, {workoutName : 'Jumping Jack'}, {workoutName : 'something (Left)'}, {workoutName : 'something (Right)'} {workoutName : 'somethingElse'}, ]Puede agrupar por la primera parte de nombre de workoutName y obtener elementos agrupados en orden como una matriz plana.
const array = [{ workoutName: 'push-up' }, { workoutName: 'plank' }, { workoutName: 'single-Leg (Left)' }, { workoutName: 'arm-extend (Right)' }, { workoutName: 'Jumping Jack' }, { workoutName: 'single-Leg (Right)' }, { workoutName: 'something (Left)' }, { workoutName: 'arm-extend (Left)' }, { workoutName: 'somethingElse' }, { workoutName: 'something (Right)' }], order = { left: 1, right: 2 }, sortReplace = s => s.replace(/^.*?(\((left|right)\))*$/i, (_, __, side = '') => order[side.toLowerCase()] || 0), sortSide = (a, b) => sortReplace(a.workoutName) - sortReplace(b.workoutName), getGroup = s => s.match(/.*?(?=(\s\(|$))/)?.[0] || '', result = Object .values(array.reduce((r, o) => { const group = getGroup(o.workoutName); if ((r[group] = r[group] || []).push(o) > 1) { r[group].sort(sortSide); } return r; }, {})) .flat(); console.log(result); .as-console-wrapper { max-height: 100% !important; top: 0; }