Typescript Array Sort
How array sort works in typescript
Let us see how we can sort an array in typescript. Suppose we have an array are mentioned below, and I want to sort it. The easiest way is the [].sort function.
arr = ['vue','angular','react']
console.log(arr.sort())
//result
//['angular','react','vue']
Sort function return type
So the surprising part is that the sort function has actually manipulated our original array. It does not return a new array. Instead, it reorders our original array.
Use Of ReadOnly
Let’s have a close look at result again and try to log the original array.
arr = ['vue','angular','react']
console.log(arr.sort())
console.log(arr)
//result
//['angular','react','vue']
//['angular','react','vue']
Sometimes we actually don't want to manipulate the original array. Rather, we want it to return a new array and that’s where we slice the array before the sort function.
let newarr = arr.slice().sort();
console.log({...arr})
console.log({...newarr})
//result
//['vue','angular','React']
//['React','angular','vue']
Another way to avoid manipulating the original array is to use read-only arrays. Read-only arrays come in action if we mark our array as read-only. We are not allowed to call the functions which can manipulate them after that point.
let arr :ReadonlyArray<string>= ['vue','angular','React'];
let newarr =arr.slice().sort();
console.log({...arr})
console.log({...newarr})
//result
//['vue','angular','React']
//['React','angular','vue']
Case sensitive sortings
When we call the sort function, we are sorting the array in alphabetical order. However, the default method of sorting is case sensitive. This means that It first sorts alphabetically all the capital letters [A-Z], and only after that has finished, it sorts the lower case letters [a-z]. We can see this in the above example. Even though ‘a’ comes before ‘R’, the ordering of the new array starts with ‘React’, since it is capitalized, and is followed by ‘angular’ and ‘vue’. This is something to keep in mind if we want to sort the list alphabetically. It may be worthwhile to convert all the characters in a string to lowercase first.
Comparer function in sort function
Now the above code will work if the array element types are strings. But for complex objects, there is a different approach. Let’s say we have an array of objects and we want to sort on a specific property. Then, in that case, we will have to pass a parameter to the sort function which is a function which accepts two things. The first one is the first value of the array and the next is the next value in that array and then we can return a.[specificproperty] — b.[specificproperty]. Let’s an example of this:
let arr = [{
name:'jhon' , year:1990
},
{
name:'kasey' , year:1985
},
{
name:'jhony' , year:1980
},
{
name:'lily' , year:1975
}]
arr.sort((a,b)=>{
return a.year - b.year
})
Summary
For More Go To : Smart Code Hub
Comments
Post a Comment