Home > Blockchain >  How to sort / re-arrange / shift JS array objects without changing original positioning
How to sort / re-arrange / shift JS array objects without changing original positioning

Time:01-03

I have an array of

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)'}

]

I would like to sort / shift the original objects to match their pairs if available in this list and keep the positioning. Like shifting the names around without breaking the current structure.

This does sort it but I need to keep the same order.

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" }
]

expected result

[
{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'},
]

CodePudding user response:

You could group by the first part of workoutName and get grouped items in order as flat array.

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)' }],
    getGroup = s => s.match(/.*?(?=(\s\(|$))/)?.[0] || '',
    result = Object
        .values(array.reduce((r, o) => {
            const group = getGroup(o.workoutName);
            (r[group] = r[group] || []).push(o);
            return r;
        }, {}))
        .flat();

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

  • Related