// Sort an array of numbers based on numerical value.
let numbers = [23, 65, 88, 12, 45, 99, 2000]
let sortednumbers = numbers.sort((a, b) => a - b);
//=> [12, 23, 45, 65, 88, 99, 2000]
//sort is function in js which sort according to alphanumerical
//for array with number it is little twist
const items= ["Banana","Orange","Apple"];
const ratings = [92,52,2,22]
console.log(items.sort())// reuturn ["Apple","Banana","Orange]
//for array with number
ratings.sort(function(a,b){
return a-b; //ascending for decending b-a
// return is negative a is sorted befor b
// positive b is sorted before a
// if they are the same is 0 then nothing changes.
})
const myNumbers = [0, 3.14, 2.718, 13];
myNumbers.sort(function (a, b) {
return a - b;
/* If a less than b, a negative number will be returned.
It means that a is to be placed before b in the final array. For example:
a = 0, b = 3.14
a - b = -3.14
Received a negative number, so a goes before b */
});
console.log(myNumbers); // [0, 2.718, 3.14, 13] — correct
var reA = /[^a-zA-Z]/g;
var reN = /[^0-9]/g;
function sortAlphaNum(a, b) {
var aA = a.replace(reA, "");
var bA = b.replace(reA, "");
if (aA === bA) {
var aN = parseInt(a.replace(reN, ""), 10);
var bN = parseInt(b.replace(reN, ""), 10);
return aN === bN ? 0 : aN > bN ? 1 : -1;
} else {
return aA > bA ? 1 : -1;
}
}
console.log(
["A1", "A10", "A11", "A12", "A2", "A3", "A4", "B10", "B2", "F1", "F12", "F3"].sort(sortAlphaNum)
)