在 JavaScript 中对数组进行排序并将特定元素作为默认值

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/5 23:40:17

我们需要编写一个 JavaScript 函数,该函数将文字值数组作为第一个参数,将字符串作为第二个参数。

我们的函数应按字母顺序对数组进行排序,但将提供的字符串作为第二个参数(如果数组中存在)作为第一个元素,而不管它包含什么文本。

示例

其代码为 −

const arr = ["Apple", "Orange", "Grapes", "Pineapple", "None", "Dates"];
const sortKeepingConstants = (arr = [], text = '') => {
   const sorter = (a, b) => {
      return (b === text) - (a === text) || a.localeCompare(b);
   }
   arr.sort(sorter);
};
sortKeepingConstants(arr, 'None');
console.log(arr);

输出

控制台中的输出将是 −

[ 'None', 'Apple', 'Dates', 'Grapes', 'Orange', 'Pineapple' ]

相关文章


有用资源