在 JavaScript 中按相反顺序对字符串进行排序

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/5 16:44:17

我们需要编写一个 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

相关文章


有用资源