The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
// Functionless sort()
// Arrow function sort((a, b) => { /* ... */ } )
// a is the first element for comparison and b is the second element for
// comparison.
Parameters in the sort() method specify a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
Note that the array is sorted in place, and no copy is made.
The answer you need might be the answer given below or nearly corresponds to it.
The sort method can be conveniently used with function expressions:
const numbers = [1, 2, 3];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers);
// [3, 2, 1]
This perfectly reverses an array with any count of numbers you have.
For reference, you can read sort() method documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#:~:text=The%20sort%20method%20can%20be%20conveniently%20used%20with%20function%20expressions%3A
Answer from Sharjeel Faiq on Stack Overflowjavascript - JS .reverse array using .sort - a trick which doesn't seem to work? - Stack Overflow
Sorting strings in descending order in Javascript (Most efficiently)? - Stack Overflow
How can I reverse an array in JavaScript without using libraries? - Stack Overflow
Why does sort and reverse an array in Javascript give the desired output - Stack Overflow
Videos
The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is ascending, built upon converting the elements into strings, then comparing their sequences of UTF-16 code units values.
// Functionless sort()
// Arrow function sort((a, b) => { /* ... */ } )
// a is the first element for comparison and b is the second element for
// comparison.
Parameters in the sort() method specify a function that defines the sort order. If omitted, the array elements are converted to strings, then sorted according to each character's Unicode code point value.
Note that the array is sorted in place, and no copy is made.
The answer you need might be the answer given below or nearly corresponds to it.
The sort method can be conveniently used with function expressions:
const numbers = [1, 2, 3];
numbers.sort(function(a, b) {
return b - a;
});
console.log(numbers);
// [3, 2, 1]
This perfectly reverses an array with any count of numbers you have.
For reference, you can read sort() method documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort#:~:text=The%20sort%20method%20can%20be%20conveniently%20used%20with%20function%20expressions%3A
The comparison function will swap the elements if the comparison function returns negative . so, just change the ` const trickReverse = arr => arr.sort(e => -1);
console.log(trickReverse([1, 2, 3])); -> [ 3,2,1] ` This will do the trick
For reference
If you consider
obj.sort().reverse();
VS
obj.sort((a, b) => (a > b ? -1 : 1))
VS
obj.sort((a, b) => b.localeCompare(a) )
The performance winner is : obj.sort().reverse().
Testing with an array of 10.000 elements,
obj.sort().reverse()is faster thanobj.sort( function )(except on chrome), andobj.sort( function )(usinglocalCompare).
Performance test here :
var results = [[],[],[]]
for(let i = 0; i < 100; i++){
const randomArrayGen = () => Array.from({length: 10000}, () => Math.random().toString(30));
const randomArray = randomArrayGen();
const copyArray = x => x.slice();
obj = copyArray(randomArray);
let t0 = performance.now();
obj.sort().reverse();
let t1 = performance.now();
obj = copyArray(randomArray);
let t2 = performance.now();
obj.sort((a, b) => (a > b ? -1 : 1))
let t3 = performance.now();
obj = copyArray(randomArray);
let t4 = performance.now();
obj.sort((a, b) => b.localeCompare(a))
let t5 = performance.now();
results[0].push(t1 - t0);
results[1].push(t3 - t2);
results[2].push(t5 - t4);
}
const calculateAverage = x => x.reduce((a,b) => a + b) / x.length ;
console.log("obj.sort().reverse(): " + calculateAverage(results[0]));
console.log("obj.sort((a, b) => (a > b ? -1 : 1)): " + calculateAverage(results[1]));
console.log("obj.sort((a, b) => b.localeCompare(a)): " + calculateAverage(results[2]));
Using just sort and reverse a > Z , that is wrong if you want to order lower cases and upper cases strings:
var arr = ["a","b","c","A","B","Z"];
arr.sort().reverse();
console.log(arr)//<-- [ 'c', 'b', 'a', 'Z', 'B', 'A' ] wrong!!!
English characters
var arr = ["a","b","c","A","B","Z"];
arr.sort((a,b)=>b.localeCompare(a))
console.log(arr)
Special characters using locales, in this example es (spanish)
var arr = ["a", "á", "b","c","A","Á","B","Z"];
arr.sort((a, b) => b.localeCompare(a, 'es', {sensitivity: 'base'}))
console.log(arr)
sensitivity in this case is base:
Only strings that differ in base letters compare as unequal. Examples: a ≠ b, a = á, a = A.
Javascript has a reverse() method that you can call in an array
var a = [3,5,7,8];
a.reverse(); // 8 7 5 3
Not sure if that's what you mean by 'libraries you can't use', I'm guessing something to do with practice. If that's the case, you can implement your own version of .reverse()
function reverseArr(input) {
var ret = new Array;
for(var i = input.length-1; i >= 0; i--) {
ret.push(input[i]);
}
return ret;
}
var a = [3,5,7,8]
var b = reverseArr(a);
Do note that the built-in .reverse() method operates on the original array, thus you don't need to reassign a.
Array.prototype.reverse()is all you need to do this work. See compatibility table.
var myArray = [20, 40, 80, 100];
var revMyArr = [].concat(myArray).reverse();
console.log(revMyArr);
// [100, 80, 40, 20]