Sorting array of object based on range of Numbers of String [closed]

You could take an offset for Under and + quantifier and take the value, depending on the sorting position. Then return the delta of values or the delta of the offset.

Later, you could build a new object with sorted keys.

var object = { "60+": 0.1413972485314015, "18-29": 0.0832178903621611, "40-49": 0.1033361204013377, "30-39": 0.0835906328864075, "Under 18": 0.1326368677036551, "50-59": 0.1224973366151133 },
    keys = Object
        .keys(object)
        .sort((a, b) => {
            function getV(s, side) {
                var offset = { 'Under': -1, null: 0, '+': 1 }[s.match(/Under|\+/)],
                    value = s.match(/\d+/g)[offset && side];
                return { value, offset };
            }
            
            var aa = getV(a, 1),
                bb = getV(b, 0);

            return aa.value - bb.value || aa.offset - bb.offset;
        }),
   newObject = Object.assign(...keys.map(k => ({ [k]: object[k] })));

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

Leave a Comment