1numArray.sort((a, b) => a - b); // For ascending sort
2numArray.sort((a, b) => b - a); // For descending sort
1let numbers = [4, 10, 5, 1, 3];
2numbers.sort((a, b) => a - b);
3console.log(numbers);
4
5// [1, 2, 3, 4, 5]
1var fruits = ["Banana", "Orange", "Apple", "Mango"];
2fruits.sort(); // Sorts the elements of fruits
1var arr = [23, 34343, 1, 5, 90, 9]
2
3//using forEach
4var sortedArr = [];
5arr.forEach(x => {
6 if (sortedArr.length == 0)
7 sortedArr.push(x)
8 else {
9 if (sortedArr[0] > x) sortedArr.unshift(x)
10 else if (sortedArr[sortedArr.length - 1] < x) sortedArr.push(x)
11 else sortedArr.splice(sortedArr.filter(y => y < x).length, 0, x)
12 }
13})
14console.log(sortedArr);
15
16
17// using sort method
18console.log(arr.sort((a,b)=>{
19 return a-b;
20}));
21