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