Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
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.
Understanding the Problem
We need to sort an array so that all minors (ages
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);
[ 16, 12, 4, 8, 3, 23, 56, 56, 67, 34, 23, 67, 47 ]
How It Works
The custom comparator function `sorter` works by:
- Returning -1 when the first element is less than 18 (moves it to front)
- Returning 1 when the second element is less than 18 (keeps first element back)
- Returning 0 when both are adults (maintains original order)
Alternative Approach Using Partition
Here's another method that explicitly separates minors and adults:
const ages2 = [23, 56, 56, 3, 67, 8, 4, 34, 23, 12, 67, 16, 47];
const partitionByAge = arr => {
const minors = arr.filter(age => age < 18);
const adults = arr.filter(age => age >= 18);
return minors.concat(adults);
};
const result = partitionByAge(ages2);
console.log(result);
[ 3, 8, 4, 12, 16, 23, 56, 56, 67, 34, 23, 67, 47 ]
Comparison
| Method | Memory Usage | Time Complexity | Modifies Original |
|---|---|---|---|
| Custom Sort | O(1) extra | O(n log n) | Yes |
| Filter & Concat | O(n) extra | O(n) | No |
Conclusion
Use the custom sort approach when you need to modify the original array in-place. The filter method is cleaner but creates a new array, using extra memory.
Advertisements
