Create several homogeneous arrays from a larger heterogenous array efficiently 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 =&gt; aircraft.status === 'SERVICEABLE');

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

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

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

splitLists(aircraft);
Ideally, you would want a groupBy function, such as the _.groupBy() function offered by lodash.  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);