locked
Create separate arrays based upon a customer ID in angular.forEach RRS feed

  • Question

  • User1793652459 posted

    I get data from SQL and loop through the incoming records. One of my requirements is to group some data based upon a customer ID. For example track Purchase Orders based upon customer ID.  So Data could be presented in a HTML table like this, here is a simplified version of what users would like to see:

    CustomerID...........Purchase Oder
    001..................712223
    .........................712224
    002..................882223
    .........................882224
    003..................992223
    .........................992224
    .........................992223
    ..........................992225

    How can I build an array, based upon the CustomerID and group records together so I can display data in the above format.
    angular.forEach($scope.requests, function (value, key) {
                           var GetPO = value.POnumber
                            var POs = [];
                            //How do I add value.CustID to group POs based upon the CustID. 
                            POs.push(GetPO);
                            console.log(POs)

    Of course problem is, it's combining all PO numbers since I am not providing any CustomerID filter.  Not sure how do I add the filter to create a PO array based upon the CustomerID. 

    Thanks

    Friday, April 6, 2018 6:22 PM

Answers

  • User-474980206 posted

    you want an array of arrays. assuming $scope.resuests is an array:

    // an array of an array of ponumbrs indexed custid
    // customers[custid][0] == first ponumber
    var customers = $scope.requests.reduce(function(p,c) {
       p[c.CustID] = (p[c.CustID] || []).push(c.PONumber);
       return p;
    },[]);
    
    console.log(JSON.stringify(customrs,4);
    
    // an array customer object with an arry of ponumbrs 
    // customers[0][0] == first customer, first ponumber
    var customers = $scope.requests.reduce(function(p,c) {
       var cust = p.find(function(r) { return r.CustID == c.CustID});
       if (!cust) {
          cust = {CustID: c.CustID, PONumbers=[]};
          p.push(cust); 
       }
       cust.PONumbers.push(c.PONumber);
       return p;
    },[]);
    
    console.log(JSON.stringify(customrs,4);
    
    //use angular foreach
    var customers = [];
    angular.forEach($scope.requests, function (c, k) {
       var cust = customers.find(function(r) { return r.CustID == c.CustID)};
       if (!cust) {
          cust = {CustID: c.CustID, PONumbers=[]};
          customers.push(cust); 
       }
       cust.PONumbers.push(c.PONumber);
    });
    


      

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, April 6, 2018 9:47 PM