Skip to main content
edited title
Link
200_success
  • 145.6k
  • 22
  • 191
  • 481

How to optimize creating 4 arrays out of 1 Partitioning an array? of objects into four arrays by one attribute

Source Link
Leon Gaban
  • 367
  • 2
  • 9

How to optimize creating 4 arrays out of 1 array?

I have an array of API objects, below is an example of one object:

{
    description: "Get a list of most recent social alerts"
    example_input: ""
    example_output: "status"
    id: 19
    method: "GET"
    resource: "/api/alerts"
}

With my code below, I'm able to loop through the big Array, then filter out items into 1 of 4 arrays (for GET, POST, PUT and DELETE)

RestFactory.getREST().then(function(res) {
    filterArrays(res.data.rest_methods);
});

function filterArrays(data) {
    for (var i=0; i<data.length; i++) {
        if (data[i].method === 'GET') {
            getArray.push(data[i]);
        }
        else if (data[i].method === 'POST') {
            postArray.push(data[i]);
        }
        else if (data[i].method === 'PUT') {
            putArray.push(data[i]);
        }
        else if (data[i].method === 'DELETE') {
            deleteArray.push(data[i]);
        }
    }
}

I feel that this is not the most efficient way to accomplish this, how should this be refactored? Would you recommend lodash in this scenario?