python ruby-programming-language Smalltalk Vue.js Knockoutjs TypeScript JavaScript, OOPs JavaScript Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 8,7,6,5,4 and 2 Interview Questions and Answers Angular 4 Angular 2 AngularJs 1.x NodeJs Perl Programming R Programming RequireJs Rust Programming Backbonejs closure programming language go-programming-language kotlin-programming-language

sorting array in JavaScript

Hi All, I'm going to explain to sorting array in JavaScript.

Today's, I have a requirement to sorting array using JavaScript.

JavaScript have to Array.sort() method is default ascending order.

var empArray = ['x', 'a', 'z', ‘b’];
empArray.sort();

//Output: a, b, x and z.

These Code samples are working on mostly all browsers (IE, Mozilla, and Firefox etc.)

In the 1st step, Code Sample for JavaScript sorting Array objects

<script type="text/javascript" lang="ja">
     //Employee array collections.
    var employeeArray = [
        { empName: "Anil", empEmail: "[email protected]", empAge: 29 },
        { empName: "Sunil", empEmail: "[email protected]", empAge: 22 },
        { empName: "Sushil", empEmail: "[email protected]", empAge: 19 },
        { empName: "Reena", empEmail: "[email protected]", empAge: 23 },
        { empName: "Tinko", empEmail: "[email protected]", empAge: 20 }
    ];

    //Method : sorting by ascending order by Email
    function orderByEmpEmailAscending(p, q) {
        if (p.empEmail == q.empEmail) {
            return 0;
        } else if (p.empEmail > q.empEmail) {
            return 1;
        }
        return -1;
    }
    //Method : sorting by ascending order by Age
    function orderByEmpAgeAscending(p, q) {
        return p.empAge - q.empAge;
}

    //Used to array.sort() method.
    employeeArray.sort(orderByEmpEmailAscending);
    employeeArray.sort(orderByEmpAgeAscending);
   
</script>



ANIL SINGH

Hi there! Welcome to my blog. My name is Anil Singh. I'm a author of this blog. For more detail about me, kindly refer to this link..
My Blogs - http://code-sample.com and http://code-sample.xyz
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like
www.code-sample.com/. Powered by Blogger.
ASK Questions