0

I have two array objects which is of different lengths in which data.rows is of length 955 and place_names is of length 287. I am running loop inside the loop which takes around 3 minutes to run. Is there any easy and fastest way to run the code below?

for (i = 0; i < place_names.length; i++) {
  for (j = 0; j < data.rows.length; j++) {
    if (place_names[i].name === data.rows[j].name) {
      geom.push(data.rows[j].st_asgeojson);
      geom1.push({
        name: data.rows[j].name,
        geometry: data.rows[j].st_asgeojson
      });
      matched_average_value.push(place_names[i].average);
      matched_sum_value.push(place_names[i].sum);
      matched_minimum_value.push(place_names[i].minmum);
      matched_maximum_value.push(place_names[i].maximum);
    }
    else {
      console.log("no matches found");
    }
  }
}
18
  • You can try this and compare. But I don't think it is gonna make much difference. Fiddle: jsfiddle.net/xoowvcf9 Commented Dec 17, 2015 at 12:43
  • 1
    are i and j local variables ? you could sort both list by name. Commented Dec 17, 2015 at 12:43
  • @Hacketo, Sorting will go through another loop right ? But that won't be nested one. Kind of helpful! Also you somewhere need to break a loop I suppose. if (place_names[i].name === data.rows[j].name) here ? Commented Dec 17, 2015 at 12:46
  • @RayonDabre sorting would allow to stop inner loop when reach the last item that match, and you could start the inner loop at the last item that previously match. Commented Dec 17, 2015 at 12:46
  • 1
    remove the console.log ... where you have it will result in up to 274000+ pointless console.logs Commented Dec 17, 2015 at 12:47

1 Answer 1

0

You have two lists place_names and data.rows. The field you're interested in is the name field.

Depending on where you get this data from, it might be better to use a dictionary for this:

var dict = {};
place_names.forEach(
    function(place_name) {
        dict[place_name.name]=place_name;
    }
);

Now you can loop through your data.rows:

data.rows.forEach(
    function(row) {
        if(row.name in dict) {
            var place_name = dict[row.name];
            // Do what needs to be done with "row" and "place_name"
        }
    }
);

This should reduce your n^2 algorithm to a n log n or even n (Depending on JavaScript's dictionary indexing complexity, I'm not sure). This solution assumes that all place_names[i].name values are unique. If they aren't, then you might want to store a list of all matching place_names in your dict.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.