如何在 JavaScript 中根据年龄对数组进行排序?

javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/24 12:28:17

我们需要编写一个 JavaScript 函数,该函数接受一个表示某些人年龄的数字数组。

然后,该函数应将所有年龄小于 18 岁的人放在数组的最前面,而不使用任何额外的内存。

示例

其代码为 −

const ages = [23, 56, 56, 3, 67, 8, 4, 34, 23, 12, 67, 16, 47];
const sorter = (a, b) => {
   if (a < 18) {
      return -1;
   };
   if (b < 18) {
      return 1;
   };
   return 0;
}
const sortByAdults = arr => {
   arr.sort(sorter);
};
sortByAdults(ages);
console.log(ages);

输出

控制台中的输出 −

[
   16, 12, 4, 8, 3, 23, 56,
   56, 67, 34, 23, 67, 47
]

相关文章


有用资源