xxxxxxxxxx
// how to sort array numbers in javascript without mutating original array.
const numbers = [100, 25, 1, 5];
const sorted = numbers.slice().sort((a, b) => a - b); // returns a new sorted array
console.log(numbers); // [100, 25, 1, 5]
console.log(sorted); // [1, 5, 25, 100]
xxxxxxxxxx
// javascript sort numbers
let numbers = [7, 56, 11, 32, 42, 79];
numbers.sort((a, b) => a - b);
console.log(numbers)
// javascript sort alphabet
let array = ["d", "c", "b", "a"];
array.sort((a, b) => a.localeCompare(b));
console.log(array);
xxxxxxxxxx
const bignumbers = [66, 58, 81, 444, 92, 9, 6, 13, 2];
const sortedNumbers = bignumbers.sort(function (a, b) {
return a - b;
})
console.log(sortedNumbers);
//Output: [2, 6, 9, 13, 58,66, 81, 92, 444]
xxxxxxxxxx
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
// Array(3) [ 99, 104, 140000 ]
xxxxxxxxxx
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
xxxxxxxxxx
[0,10,4,9,123,54,1].sort((a,b) => a-b);>>> [0, 1, 4, 9, 10, 54, 123]
xxxxxxxxxx
//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.
})
xxxxxxxxxx
const numbers = [4, 2, 5, 1, 3];
numbers.sort(function(a, b) {
return a - b;
});
console.log(numbers);
// [1, 2, 3, 4, 5]
xxxxxxxxxx
var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});
console.log(numArray);
Run code snippet