1
@api weekdaySelectionData=[];

The below is coming through data table, but  I just want to sort the final list:

weekdaySelectionData=[{"Day__c":"Tue","Morning__c":true,"Afternoon__c":false,"Evening__c":false},{"Day__c":"Mon","Morning__c":true,"Afternoon__c":false,"Evening__c":false},{"Day__c":"Thurs","Morning__c":true,"Afternoon__c":false,"Evening__c":false}]

How to sort this list? I would like to have Mon as on 1st index, then tue then thurs.

PLease help..Thanks a ton in advance.

2
  • 2
    You can write your own custom sorting logic using the .sort() method: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…. In case you are querying the records consider adding an Order By clause to the SOQL to sort it out at the Apex side itself
    – Sam
    May 3, 2021 at 9:50
  • could you please share the code for the above, I mean it is not from SOQL. It is taking user input only.
    – user91530
    May 3, 2021 at 9:52

1 Answer 1

0

You need to define a custom sort method like this.

const indexes = {
    Mon: { index: 1 },
    Tue: { index: 2 },
    Wed: { index: 3 },
    Thurs: { index: 4 },
    Fri: { index: 5 },
    Sat: { index: 6 },
    Sun: { index: 7 }
};
export default class YourComponentName extends LightningElement {

    //... other code

    weekdaySelectionData = [
        {
            Day__c: "Tue",
            Morning__c: true,
            Afternoon__c: false,
            Evening__c: false
        },
        {
            Day__c: "Mon",
            Morning__c: true,
            Afternoon__c: false,
            Evening__c: false
        },
        {
            Day__c: "Thurs",
            Morning__c: true,
            Afternoon__c: false,
            Evening__c: false
        }
    ];

    get sortedData() {
        return this.weekdaySelectionData.sort((a, b) => {
            let dayA = indexes[a.Day__c].index;
            let dayB = indexes[b.Day__c].index;
            return dayA - dayB;
        });
    }
}

Just use or modify the sortedData to get the sorted elements. Also if you want to change the order or names of days the modify the indexes global constant. Please note that the keys are case SeNsiTIVe

Here is the playground for this example

4
  • Thanks for sharing the code but I am not getting the same output.. i think the message is not getting called.
    – user91530
    May 5, 2021 at 12:04
  • 1
    Sorry just now edited the API name. It was wrongly typed.. Thanks a ton for your help. Really greatful to you :) thanks alot.
    – user91530
    May 5, 2021 at 12:16
  • 1
    @Rahul - The 'sortedData()' can further be reduced to just a single line with ES6 notations as return this.weekdaySelectionData.sort((a, b) => indexes[a.Day__c].index - indexes[b.Day__c].index);
    – Saroj Bera
    May 18, 2021 at 10:11
  • @SarojBera great, thanks! May 18, 2021 at 10:44

Not the answer you're looking for? Browse other questions tagged .