1// Sort an array of numbers based on numerical value.
2let numbers = [23, 65, 88, 12, 45, 99, 2000]
3
4let sortednumbers = numbers.sort((a, b) => a - b);
5//=> [12, 23, 45, 65, 88, 99, 2000]
1var numArray = [140000, 104, 99];
2
3numArray.sort(function(a, b) {
4 return a - b;
5});
6
7// Array(3) [ 99, 104, 140000 ]
1const months = ['March', 'Jan', 'Feb', 'Dec'];
2months.sort();
3console.log(months);
4// expected output: Array ["Dec", "Feb", "Jan", "March"]
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