HiveBrain v1.2.0
Get Started
← Back to all entries
snippetjavascriptMinor

Create several homogeneous arrays from a larger heterogenous array efficiently

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
efficientlyarraysheterogenouslargercreatearrayhomogeneousseveralfrom

Problem

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);

Solution

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);

Context

StackExchange Code Review Q#157864, answer score: 3

Revisions (0)

No revisions yet.