0

I am using expressjs to render my routes and pass on database information.

  • I have two arrays 1. paintingJobs 2. customerList .
  • The (1) paintingJobs array has a foreign key, which contains the customer ID.
  • I want to create an array of customers who currently HAVE painting jobs and pass that array onto the view
  • . To filter the (2)customerList array down to a list of only those customers who currently have painting jobs; I use a series of nested for loops like so.....

         for(var i=0; i<paintingJobs.length; i++) {
            for(j=0; j<customerList.length; j++) {
                if (customerList[j].ID == paintingJobs[i].CustomerID) {
                    customerRecords.push(customerList[j]);
                }
            }
         }
    

    Creating the new filtered array of customerRecords, which is then passed to the view.

    My Question is: If I sort the (1)paintingJobs array by date prior to using it as a filter for my (1)customerList, will the resulting array (customerRecords) be sorted by date as well or more specifically is this a reliable method? If not, would appending the date to the customerList and then sorting the final array be the next best solution?

    I am passing this information to my view and then creating an Unordered List based on the number of records.

    Thank you for your time and any suggestions

  • 4

    2 回答 2

    1

    Your double-loop preserves the order of paintingJobs in customerRecords, though unless you have duplicate customerList ID's, looks somewhat inefficient (why no break?).
    This means changes to the order of paintingJobs before your double loop will be reflected in customerRecords. Changes after will not.

     paintingJobs.sort(however);
    
     for(var i=0; i<paintingJobs.length; i++) {
        for(j=0; j<customerList.length; j++) {
            if (customerList[j].ID == paintingJobs[i].CustomerID) {
                customerRecords.push(customerList[j]);
                break; // next paintingJob
            }
        }
     }
    

    It looks like the items in customerList are Objects, so if you make a change to an Object in customerList, this change will also appear in customerRecords even after your double loop.

    于 2013-08-08T11:43:09.287 回答
    1

    This is not a answer to your original question, but concerning performance i would create something like a test- object with the ID as key,like

    for(var i=0; i<paintingJobs.length; i++) {
    testArray[paintingJobs[i].ID] += 1;
    }
    
    for(j=0; j<customerList.length; j++) {
    testArray[customerList[j].ID] += 1;
    }
    

    and check where the testObject has the value 2. Then with these keys run your operations. This method will be MUCH faster as your nested loop.

    于 2013-08-08T11:55:44.720 回答