today I was writing some code and I realized I cannot do
x.push(5, 9).sort(); //wrong
nor can I do
x.sort(x.push(5, 9)); //wrong
and had to do
x.push(5, 9);
x.sort();
I was wondering isn't there a way to make it one line?> also, what's the difference between the two lines below
x.sort((a, b) => a - b);
x.sort();
CodePudding user response:
.push
returns the new length of the array, not the mutated array. If you want to push and sort at the same time, consider creating a new array, then sorting that.
const sortedArr = [...arr, 5, 9].sort();
// or, .sort((a, b) => a - b)
.sort()
without any arguments sorts each item in the array by comparing them lexiographically, as strings - resulting in unintuitive results like [1, 11, 2]
.
A custom callback allows you to customize the behavior - when an element of an array is compared against another, instead of using lexiographic comparison, the callback is invoked, and whether the return value is negative, positive, or 0 determines whether the two items get sorted before, after, or at the same (relative) position to the other. So, when sorting an array of numbers numerically, you always want to use something like (a, b) => a - b
.
CodePudding user response:
Another way to push and sort in one line is to use concat
to create a new array which can be then be sorted:
const arr = [1, 6, 10]
const sortedArr = arr.concat([5, 9]).sort((a, b) => a - b)
console.log(sortedArr)
As @CertainPerformance has already noted, you must use a callback to correctly sort numeric values as string sorting of numbers produces incorrect results.