以相反順序對 JavaScript 中的字串排序
我們要編寫一個 JavaScript 函式,該函式採用一個小寫字串,並按相反的順序對它進行排序,即,b 應在 a 之前,c 在 b 之前,依次類推。
例如:如果輸入字串為 −
const str = "hello";
那麼輸出應該是 −
const output = "ollhe";
示例
以下是程式碼 −
const string = 'hello'; const sorter = (a, b) => { const legend = [-1, 0, 1]; return legend[+(a < b)]; } const reverseSort = str => { const strArr = str.split(""); return strArr .sort(sorter) .join(""); }; console.log(reverseSort(string));
輸出
以下是控制檯中的輸出 −
ollhe
廣告