
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements