0

I'm practicing my shorthand code writing.

Originally the code goes like

function sort(sortBy: String) {
    SortByAscending = !SortByAscending
    rankingList.sort((a: any, b: any) => {
        if(sortBy == 'name')
        return a.name < b.name ? SortByAscending ? -1 : 1 : SortByAscending ? 1 : -1
        if(sortBy == 'age')
        return a.age < b.age ? SortByAscending ? -1 : 1 : SortByAscending ? 1 : -1
    }
    );
}

instead of writing "if(sortBy == etc)", is there a way to use template literal like

function sort(sortby: String) {
    SortByAscending = !SortByAscending
    rankingList.sort((a: any, b: any) => {
        return a.`${sortby}` < b.`${sortby}` ? SortByAscending ? -1 : 1 : SortByAscending ? 1 : -1
    }
    );
}

using the argument as the string?

  • 2
    `a.\`.......\``??? you mean `a[sortBy]` perhaps - template literals are a new toy, but they don't replace the old toys – Bravo May 06 '22 at 02:07

0 Answers0