如何升级JavaScript自定义sort函数以支持基于isAscending参数的升降序切换
Upgrade Sort Function to Support Toggleable Ascending/Descending Order
No problem at all—let's tweak your existing sortArrayBy function to respect the new isAscending boolean parameter. The core idea is to keep your original value comparison logic intact, then flip the result when we need a descending sort.
Here's the cleaned-up, upgraded version:
sortArrayBy: function(a, b, sortKey, isAscending) { // Get the base ascending comparison result first let compareResult = 0; if (a[sortKey] < b[sortKey]) { compareResult = -1; } else if (a[sortKey] > b[sortKey]) { compareResult = 1; } // Toggle direction if descending is requested; default to ascending if isAscending is missing return isAscending !== false ? compareResult : -compareResult; }
Quick breakdown of the changes:
- We split the core value comparison from the sort direction logic, making the code easier to read and tweak later.
- If
isAscendingistrueor not provided (undefined), we stick with your original ascending behavior—so this maintains full backward compatibility with any existing calls that don't pass the fourth parameter. - When
isAscendingis explicitlyfalse, we invert the comparison result to get a descending sort.
Usage examples:
- Ascending sort (matches your original function's behavior):
productArray.sort((a, b) => sortArrayBy(a, b, 'price', true)); - Descending sort:
productArray.sort((a, b) => sortArrayBy(a, b, 'price', false)); - Default ascending (no need to pass the
isAscendingparameter):productArray.sort((a, b) => sortArrayBy(a, b, 'price'));
内容的提问来源于stack exchange,提问作者copenndthagen
相关产品推荐
相关产品推荐

