简体   繁体   中英

Really confused about sort in JS

today I was writing some code and I realized I cannot do x.push(5, 9).sort(); //wrong x.push(5, 9).sort(); //wrong nor can I do x.sort(x.push(5, 9)); //wrong 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();

.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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM