Home > database >  JS .reverse array using .sort - a trick which doesn't seem to work?
JS .reverse array using .sort - a trick which doesn't seem to work?

Time:04-21

I want to get the same results which method Array.prototype.reverse() gives. I found this trick using .sort(), but it doesn't work in my Chrome console. Why doesn't this code reverse an array?

const trickReverse = arr => arr.sort(x => 1);

console.log(trickReverse([1, 2, 3])); -> [1, 2, 3]

Explanation: The .sort method accepts a function that normally takes 2 arguments, in this case we don't care about them and use 'x'. That function compares the 2 elements and returns a negative number if they are in correct order, zero if they are equal, and a positive number if they are in incorrect order. Usually you give it a function that actually does something useful. In this solution we've exploited it to always return a positive number (1). So that means it will think every 2 elements that are compared are in the wrong order, hence reversing the entire array.

CodePudding user response:

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

CodePudding user response:

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 sort method can be conveniently used with function expressions:

  • Related