• Search form is empty!

  • 019 TypeScript - array.sort method

    http://robertdunaway.github.io

    TypeScript code kata list

    All code kata lists

    Smiley face

    019 TypeScript - array.sort method

    Duration

    10 minutes

    Brief

    Creating a sorter for an array.

    For more information

    BING/GOOGLE: “TypeScript array sort”

    Instructions

    Get tutorial folder or the entire katas-typescript repo.
    Open the [before/*.sln] file and execute the kata.
    Feel free to execute this kata multiple times because repetition creates motor memory.

    Github

    Kata

    Create a simple interface.


    
        interface pet {
            name: string;
            age: number;
            weight: number;
        }
    
    


    Popular a new array based on the new interface.


    
        var myPets: pet[] = [
            { name: 'Sally', age: 18, weight: 85 },
            { name: 'Jasmine', age: 9, weight: 55 },
            { name: 'Rush', age: 15, weight: 45 },
            { name: 'Roxie', age: 6, weight: 85 }
        ];
    
    


    Create a comparer based on age.


    
        var compareAge = function (a: pet, b: pet) {
            if (a.age > b.age) { return -1; }
            if (a.age < b.age) {return 1; }
            return 0;
        }
    
    


    Output the sorted array to the console.


    
        console.log(myPets.sort(compareAge));
    
    


    Create a comparer based on weight.


    
        var compareWeight = function (a: pet, b: pet) {
            if (a.weight > b.weight) { return -1; }
            if (a.weight < b.weight) { return 1; }
            return 0;
        }
    
    


    Output the sorted array to the console.


    
        console.log(myPets.sort(compareWeight));
    
    


    Smiley face

    Next

    Take a few minutes and imagine more examples.

    Smiley face

    0 comments:

    Post a Comment