0
votes

Working on the new Salesforce Lightning web components. I am trying to get the multidimensional array sorted in javascript. I have a trackable array, it has a few columns, i want the data sorted by the total buildings value. Here is what I have done so far, no errors, but not getting the expected results.

@track bc = [];
@wire(getCityStats) cityStats({ data }) {
    if (data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].sumchans__Province_Code__c == 'BC') {
          this.bc.push(data[i]);
        }
      }
      sortCityByNumberOfBldgs(this.bc);
}
}
  sortCityByNumberOfBldgs(province) {
    province.sort(function(a,b) {
      return a[4]-b[4]
    });
  } 

Here is the SOQL in the Apex controller:

SELECT Name,sumchans__Province_Code__c,
        (select sumchans__Penetration__c,sumchans__Total_Buildings__c from sumchans__City_Stats__r) FROM sumchans__CITY_MASTER__c

This is how the data gets displayed when I run the above query and this is the data that is getting stored in the trackable bc array above. enter image description here

1

1 Answers

0
votes

simply implement a comparator:

compareASC(firstVal, secondVal) {
    
    if (firstVal.sumchans__City_Stats__r.sumchans__Total_Buildings__c > secondVal.sumchans__City_Stats__r.sumchans__Total_Buildings__c) return 1;
    if (secondVal.sumchans__City_Stats__r.sumchans__Total_Buildings__c > firstVal.sumchans__City_Stats__r.sumchans__Total_Buildings__c) return -1;
    return 0;
}

and then:

let toBeSorted = JSON.parse(JSON.stringify(data));
toBeSorted.sort(compareASC);