- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 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' ]
Advertisements