xxxxxxxxxx
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits
xxxxxxxxxx
const ascending: any= values.sort((a,b) => (a > b ? 1 : -1));
const descending: any= values.sort((a,b) => (a > b ? -1 : 1))
xxxxxxxxxx
//^ merge and sort arrays in JS
const array1 = [1, 2, 3, 5, 9, 10];
const array2 = [4, 8, 6, 7];
let sortedNewArray = [array1, array2];
sortedNewArray.sort(function (a, b) {
return a - b;
});
console.log(sortedNewArray);
xxxxxxxxxx
const items = ["réservé", "premier", "communiqué", "café", "adieu", "éclair"];
items.sort((b, a) => b.localeCompare(a));
// items is ['adieu', 'café', 'communiqué', 'éclair', 'premier', 'réservé']
xxxxxxxxxx
//ascending order
let ArrayOne = [1,32,5341,10,32,10,90]
ArrayOne = ArrayOne.sort(function(x,y){x-y})
//descending order
let ArrayTwo = [321,51,51,324,111,1000]
ArrayTwo = ArrayTwo.sort(function(x,y){y-x})
xxxxxxxxxx
function sortArray(array) {
var temp = 0;
for (var i = 0; i < array.length; i++) {
for (var j = i; j < array.length; j++) {
if (array[j] < array[i]) {
temp = array[j];
array[j] = array[i];
array[i] = temp;
}
}
}
return array;
}
console.log(sortArray([3,1,2]));
xxxxxxxxxx
var l = ["a", "w", "r", "e", "d", "c", "e", "f", "g"];
console.log(l.sort())
/*[ 'a', 'c', 'd', 'e', 'e', 'f', 'g', 'r', 'w' ]*/
xxxxxxxxxx
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// expected output: Array ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// expected output: Array [1, 100000, 21, 30, 4]