Sort an array and place a particular element as default value in JavaScript


We are required to write a JavaScript function that takes in an array of literal values as the first argument and a string as the second argument.

Our function should sort the array alphabetically but keeping the string provided as the second argument (if it exists in the array) as the first element, irrespective of the text it contains.

Example

The code for this will be −

const arr = ["Apple", "Orange", "Grapes", "Pineapple", "None", "Dates"];
const sortKeepingConstants = (arr = [], text = '') => {
   const sorter = (a, b) => {
      return (b === text) - (a === text) || a.localeCompare(b);
   }
   arr.sort(sorter);
};
sortKeepingConstants(arr, 'None');
console.log(arr);

Output

And the output in the console will be −

[ 'None', 'Apple', 'Dates', 'Grapes', 'Orange', 'Pineapple' ]

Updated on: 23-Nov-2020

271 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements