如何对含数字字符串与'LAST'的JavaScript数组按数字升序排序?
Got it, let's sort this out for you! The default sort() method in JavaScript compares values as strings by their Unicode code points, which is why you're seeing that wonky order where '10' comes before '2'. Here's a custom sort function that will give you the numeric ascending order you want, with 'LAST' always sitting at the end:
// Your example array const arr2 = ['2','1','10','LAST','20']; // Custom sort logic const sortedArray = arr2.sort((a, b) => { // Handle the 'LAST' entry first if (a === 'LAST') return 1; // Push 'LAST' to the end relative to b if (b === 'LAST') return -1; // Keep 'LAST' at the end, move a before it // Convert string numbers to actual numbers for proper numeric comparison return Number(a) - Number(b); }); console.log(sortedArray); // Output: ['1','2','10','20','LAST']
How this works:
- Handling 'LAST': We first check if either element being compared is 'LAST'. If
ais 'LAST', returning1tells the sort function to placeaafterb. Ifbis 'LAST', returning-1ensuresastays beforeb(keeping 'LAST' anchored at the end). - Numeric comparison: For all other elements, we convert the string values to numbers using
Number(). This lets us do arithmetic subtraction to determine their order—soNumber('2') - Number('10')gives-8, which means '2' comes before '10', exactly what we need for proper ascending numeric sort.
This logic will work perfectly for your original array arr (with values 1-31 plus 'LAST') as well as any similar mix of numeric strings and a 'LAST' entry. If you ever have multiple 'LAST' entries, they'll all be grouped at the end too (since comparing two 'LAST's will skip the if checks and return 0, preserving their relative order).
内容的提问来源于stack exchange,提问作者kkangil

