xxxxxxxxxx
const numbers = [4, 7, 1, 3, 6, 9, 2, 5];
const numbersSort = numbers.sort();
console.log(numbersSort);
//Output:[1, 2, 3, 4, 5, 6, 7, 9]
xxxxxxxxxx
//Higher order function for sorting
numArray.sort((a, b) => a - b); // For ascending sort
numArray.sort((a, b) => b - a); // For descending sort
const points = [40, 100, 1, 5, 25, 10];
points.sort(function(a, b){
return a - b
});
////HOF/////
numArray.sort(function(a, b){
return a - b
});
//output >> [1 ,5 , 10 ,25 ,40 ,100]
xxxxxxxxxx
const items = [
{ name: "Edward", value: 21 },
{ name: "Sharpe", value: 37 },
{ name: "And", value: 45 },
{ name: "The", value: -12 },
{ name: "Magnetic", value: 13 },
{ name: "Zeros", value: 37 },
];
items.sort(function (a, b) {
if (a.name > b.name) {
return 1;
}
if (a.name < b.name) {
return -1;
}
// a must be equal to b
return 0;
});
xxxxxxxxxx
let numbers = [0, 1 , 2, 3, 10, 20, 30 ];
numbers.sort( function( a , b){
if(a > b) return 1;
if(a < b) return -1;
return 0;
});
console.log(numbers);
Code language: JavaScript (javascript)
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
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]));