Wednesday, May 19, 2021

Javascript Practice 54: JS Hero - Sorting arrays

 
Question: 

Write a function sort that takes an array filled with 3 numbers and returns these 3 numbers sorted in ascending order as an array.

Example: sort([2, 3, 1]) should return [1, 2, 3].




Answer: 

function sort (array) {

return array.sort(function(a,b){return a - b});

}





> declare a function sort
> it has one parameter array
> we use the sort () method to sort the array elements in ascending order
> we declare a function within a function
> if we subtract b - a, then we will get the elements sorted in descending order

No comments:

Post a Comment