How to sort array according to age in JavaScript?


We are required to write a JavaScript function that takes in an array of numbers representing ages of some people.

Then the function should bring all the ages less than 18 to the front of the array without using any extra memory.

Example

The code for this will be −

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);

Output

The output in the console −

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

Updated on: 12-Oct-2020

275 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements