Learn how sorted is similar to sort but returns a sorted collection. It also is a higher order function that takes a closure. The closure also takes two parameters of the type that the collection contains. The closure returns true or false based on the comparison. The resulting sorted collection is returned from the call.
- [Instructor] So we want to look at some more…aspects of sorting.…We're going to talk about sorted.…So sorted's a little bit different.…So I'm going to delete some of this code right here,…and we're going to look at sorted.…So I'll keep my names array and I'm going to call names.sorted,…notice this has a return type, it's an array of strings,…that's the same type as names, and you'll come to understand…that that means it's going to return a sorted array of names.…It won't change names at all.…Notice the parameters, notice the return type.…
So in this case we're going to say,…let sortedNames = names.sorted.…Well there's another interesting thing,…now that it knows I'm assigning it to something,…when I go sort, there's a red line through the two…that have no return type.…It wants me to use one that has a return type.…So I could use sorted, and just like before it would do it…with the default, <,…so it would sort it in ascending order…and that's perfectly fine.…We could print out sorted and names and notice that…
- What are closures?
- Closures and function types
- Basic higher-order functions, including sort and forEach
- Powerful higher-order functions, including map and reduce
- Passing functions
- Closure optimizations
- Higher-order functions on sets, dictionaries, and strings