Sort an integer array, keeping first in place in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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]
raja
Published on 10-Dec-2020 07:36:57
Advertisements