Monday, September 10, 2018

Typescript Array Sort method with example | javascript

This blog post, We are going to learn how to Sort Array in javascript or typescript.
Typescript Array Sort method with example | javascript

Array Sort method

This method sorts the elements of an array in ascending or descending.
Elements are simple strings, Object which contains key and values or Typescript classes.

Syntax

Array.sort(ComparatorFunction)
Parameters are ComparatorFunction is a function which specifies the order of the elements, If not passed, Default sorting is applied.

Array String sort Example

Array Declared and initialized with new Array() and strings separated in comma No comparator function passed and Array.sort() method is used
var arrayStrings = new Array("one", "two", "there", "four"); 
var sortedArray = arrayStrings.sort(); 
console.log(""+sortedArray );
Output is
four,one,there,two

Object Array Sort Example ascending 

The object can be directly created using an array or you can create an Interface. This Emp object contains id and names This example sort the objects by name property First created Emp interface.
 interface Emp {
     id: number;
     name: string;
}
Next, Create Array of Objects and initialize with values
var emps: Emp[] = [
    { id: "5", name: "Kiran" },
    { id: "1", name: "Frank" },
    { id: "2", name: "Tom" },
    { id: "51", name: "Abc" }
]
And Write a Compare Function for Name of Emp object
var compareName = function (emp1: Emp, emp2: Emp) {
        if (emp1.name > emp2.name) { return -1; }
        if (emp1.name < emp2.name) {return 1; }
        return 0;
    }
 
Finally Call Array.sort() with compare function
var sortedArray = emps.sort(compareName); 
console.log(sortedArray );
Output is
0: {id: "2", name: "Tom"}
1: {id: "5", name: "Kiran"}
2: {id: "1", name: "Frank"}
3: {id: "51", name: "Abc"}

Sort Array Object Data by Date property Example

The object contains key date property. We can sort the object data based on date ascending or descending. Need to supply comparator custom code which handles Date comparisons. First Date string is converted to an Inbuilt Date object.
Date ascending 
This is an example sort array of object date by date ascending
interface Emp {
     id: number;
     name: string;
     date: Date;
}
var emps: Emp[] = [
    { id: "5", name: "Kiran",date:"2018-05-05" },
    { id: "1", name: "Frank",date:"2017-05-05"},
    { id: "2", name: "Tom",date:"2016-05-05" },
    { id: "51", name: "Abc" ,date:"2018-10-05"}
]

var compareDate = function (emp1: Emp, emp2: Emp) {
    var emp1Date = new Date(emp1.date).getTime();
    var emp2Date = new Date(emp2.date).getTime();
    return emp1Date > emp2Date ? 1 : -1;  
}
var sortedArray = emps.sort(compareDate); 
console.log(sortedArray );
Output is

0: {id: "2", name: "Tom", date: "2016-05-05"}
1: {id: "1", name: "Frank", date: "2017-05-05"}
2: {id: "5", name: "Kiran", date: "2018-05-05"}
3: {id: "51", name: "Abc", date: "2018-10-05"}
We will see the Sort Date by descending.
Date descending
var compareDate = function (emp1: Emp, emp2: Emp) {
    var emp1Date = new Date(emp1.date).getTime();
    var emp2Date = new Date(emp2.date).getTime();
    return emp1Date > emp2Date ? -1 : 1;  
}
Output is
0: {id: "51", name: "Abc", date: "2018-10-05"}
1: {id: "5", name: "Kiran", date: "2018-05-05"}
2: {id: "1", name: "Frank", date: "2017-05-05"}
3: {id: "2", name: "Tom", date: "2016-05-05"}

Underscore Array Sort Example

UnderscoreJS is a javascript library which provides a lot of utility functions. It provides sortBy function which accepts an array and a function as an argument. This library can be used in javascript or typescript applications using npm package manager installation and configuring module Here is an example of array string sorting in descending
var sortedArray=_.sortBy(["four", "one", "zero"], function (value) { return value.toLowerCase(); });
console.log(sortedArray);
output is
["four","one","zero"]

Related article


EmoticonEmoticon