Skip to content Skip to sidebar Skip to footer

How To Exclude/skip Items From Sorting?

There is an array of objects, which I need to be sorted. It looks like this: var array = [ {left: 20, top: 50, group: 'groupOne'}, {left: 18, top: 10, group: 'groupTwo'},

Solution 1:

You could group the items and sort the grouped items and then sort by the first element of the grouped item.

Later flat all groups.

var array = [{ left: 20, top: 50, group: 'groupOne' }, { left: 18, top: 10, group: 'groupTwo' }, { left: 15, top: 15, group: 'groupThree' }, { left: 25, top: 30, group: 'groupThree' }, { left: 18, top: 25, group: 'groupFour' }, { left: 28, top: 25, group: 'groupFive' }, { left: 25, top: 15, group: 'groupSix' }, { left: 30, top: 30, group: 'groupSix' }],
    leftTop = (a, b) => a.left - b.left || a.top - b.top,
    sorted = Array
        .from(
            array
                .reduce((m, o) => m.set(o.group, (m.get(o.group) || []).concat(o)), new Map)
                .values(),
            a => a.sort(leftTop)
        )
        .sort(([a], [b]) => leftTop(a, b))
        .reduce((a, b) => a.concat(b));

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

Post a Comment for "How To Exclude/skip Items From Sorting?"