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

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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.


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);
sortKeepingConstants(arr, 'None');


And the output in the console will be −

[ 'None', 'Apple', 'Dates', 'Grapes', 'Orange', 'Pineapple' ]
Updated on 23-Nov-2020 10:32:58