3
\$\begingroup\$

I have a list of aircraft returned from a REST call which describes the status of each aircraft. In order to make the UI templating simpler, this single list is split into four homogeneous lists in order to group by status.

My primary concern is that we iterate over the primary array \$s\$ times which, while still in polynomial \$O(n \times s)\$ time, feels needlessly inefficient.

Perhaps there is a way to more efficiently split this array in a single pass?

Here is a representative code sample:

let aircraft = [
    {
        tail: "9736968",
        status: "DRAFT"
    },
    {
        tail: "5114419",
        status: "SERVICEABLE"
    },
    {
        tail: "8395671",
        status: "OUTOFSERVICE"
    },
    {
        tail: "332273",
        status: "SERVICEABLE"
    },
    {
        tail: "6123961",
        status: "UNSERVICEABLE"
    },
]

let serviceable = [];
let unserviceable = [];
let outOfService = [];
let draft = [];

function splitLists(aircraftStatusList) {
    serviceable = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'SERVICEABLE');

    unserviceable = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'UNSERVICEABLE');

    outOfService = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'OUTOFSERVICE');

    draft = aircraftStatusList
                    .filter(aircraft => aircraft.status === 'DRAFT');
}

splitLists(aircraft);
\$\endgroup\$
3
\$\begingroup\$

Ideally, you would want a groupBy function, such as the _.groupBy() function offered by . If you don't want to load a library, it's not too hard to reimplement groupBy.

This solution also has the advantage of returning the result as one associative array rather than mutating four global variables as a side-effect.

let aircraft = [
    {
        tail: "9736968",
        status: "DRAFT"
    },
    {
        tail: "5114419",
        status: "SERVICEABLE"
    },
    {
        tail: "8395671",
        status: "OUTOFSERVICE"
    },
    {
        tail: "332273",
        status: "SERVICEABLE"
    },
    {
        tail: "6123961",
        status: "UNSERVICEABLE"
    },
];

// http://stackoverflow.com/a/34890276
function groupBy(collection, attr) {
    return collection.reduce(function(result, item) {
        (result[item[attr]] = result[item[attr]] || []).push(item);
        return result;
    }, {});
}

let aircraftByStatus = groupBy(aircraft, 'status');
console.log(aircraftByStatus);

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.