

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
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 ]
- Related Questions & Answers
- Sort an array according to another array in JavaScript
- Sort array according to the date property of the objects JavaScript
- Sort the second array according to the elements of the first array in JavaScript
- Sort nested array containing objects ascending and descending according to date in JavaScript
- Sort an array of strings according to string lengths in C++
- Sort an array according to count of set bits in C++
- Sort an array according to the order defined by another array in C++
- How to sort date array in JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- How to sort mixed numeric/alphanumeric array in JavaScript
- Using merge sort to recursive sort an array JavaScript
- Sort the array of strings according to alphabetical order defined by another string in C++
- How to sort an array of integers correctly JavaScript?
- How to sort an array in JavaScript?Explain with example?
- How to sort an array of integers correctly in JavaScript?
Advertisements