- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 an integer array, keeping first in place in JavaScript
We are required to write a JavaScript function that takes in an array of Numbers. The function should sort the array according to the following conditions −
array[0] should keep its place
with the next highest integer(s) following (if there are any)
then ascending from the lowest integer
For example −
If the input array is −
const arr = [10, 7, 12, 3, 5, 6];
Then the output should be −
const output = [10, 12, 3, 5, 6, 7];
Example
Following is the code −
const arr = [10, 7, 12, 3, 5, 6]; const uniqueSort = (arr = []) => { const first = arr[0]; const sorter = (a, b) => { return (a < first) - (b < first) || a - b; }; arr.sort(sorter); }; uniqueSort(arr); console.log(arr);
Output
Following is the output on console −
[10, 12, 3, 5, 6, 7]
- Related Articles
- Sort an array to have specific items first in the array - JavaScript
- Sort an array and place a particular element as default value in JavaScript
- 8086 program to sort an integer array in ascending order
- 8086 program to sort an integer array in descending order
- How to sort array by first item in subarray - JavaScript?
- Remove duplicates from an array keeping its length same in JavaScript
- Odd even sort in an array - JavaScript
- Sort an array according to another array in JavaScript
- Changing an array in place using splice() JavaScript
- Sort the masked array in-place in NumPy
- JavaScript Bubble sort for objects in an array
- Sort by index of an array in JavaScript
- Sort the second array according to the elements of the first array in JavaScript
- Comparing array elements keeping count in mind in JavaScript
- Using merge sort to recursive sort an array JavaScript

Advertisements