JavaScript Performance – Optimizing Nested For Loops

javascriptloopsperformance

I have an app which gets data from the database (MongoDB) in JSON format. The returned data contains nested arrays and I want to access the values in the nested arrays. The returned JSON format looks like this:

[
 {"_id": "81724587125","name": "Object 1", "arrayOne":["1","2","3"]},
 {"_id": "87687687687","name": "Object 2", "arrayOne":["4","5","6"]}
]

Now what I want is to retrieve the values from arrayOne from all objects and push them into a single array like so:

combinedValues:["1","2","3","4","5","6"]

To achieve this I have used Nested For Loops below is my actual code:

 function myFunc(result){

    $scope.clients = [];

    for(var i = 0; i < result.length; i++){
      for(var x = 0; x < result[i].sectorClients.length; x++){
        $scope.clients.push(result[i].sectorClients[x]);
      }
    }       
};

The above code works fine and does what I want it to do.

My Question:

Is using nested for loops for this particular situation a good programming practice? Is there a better way of achieving the same functionality? Ive heard people say that nested for loops can be "expensive" processing wise.

Best Answer

As I mentioned in the comments you can get the same result directly from MongoDB using a MapReduce query; However a cleaner JavaScript equivalent for your nested loops can be something like this:

var data = [
 {"_id": "81724587125","name": "Object 1", "arrayOne":["1","2","3"]},
 {"_id": "87687687687","name": "Object 2", "arrayOne":["4","5","6"]}
];

var result = data.reduce(function (previousValue, currentValue, currentIndex, array) {
    return previousValue.arrayOne.concat( currentValue.arrayOne );
});
Related Topic