xxxxxxxxxx
How does the following code sort this array to be in numerical order?
var array=[25, 8, 7, 41]
array.sort(function(a,b){
return a - b
})
I know that if the result of the computation is
**Less than 0**: "a" is sorted to be a lower index than "b".<br />
**Zero:** "a" and "b" are considered equal, and no sorting is performed.<br />
**Greater than 0:** "b" is sorted to be a lower index than "a".<br />
Is the array sort callback function called many times during the course of the sort?
If so, I'd like to know which two numbers are passed into the function each time. I assumed it first took "25"(a) and "8"(b), followed by "7"(a) and "41"(b), so:
25(a) - 8(b) = 17 (greater than zero, so sort "b" to be a lower index than "a"): 8, 25
7(a) - 41(b) = -34 (less than zero, so sort "a" to be a lower index than "b": 7, 41
How are the two sets of numbers then sorted in relation to one another?
Please help a struggling newbie!
xxxxxxxxxx
function ascendingOrder(arr) {
return arr.sort(function(a, b) {
return a - b;
});
}
ascendingOrder([1, 5, 2, 3, 4]);
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
//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
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
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 fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort(); // Sorts the elements of fruits