- 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 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' ]
- Related Articles
- Sort an integer array, keeping first in place in JavaScript
- Place an H1 element and its text at a particular index in jQuery
- How do I remove a particular element from an array in JavaScript
- Write a program to find the index of particular element in an array in javascript?
- Use array as sort order in JavaScript
- JavaScript: How to check whether an array includes a particular value or not?
- Mapping an array to a new array with default values in JavaScript
- Odd even sort in an array - JavaScript
- Present date as default value in a table
- Sort an array according to another array in JavaScript
- Unique sort (removing duplicates and sorting an array) in JavaScript
- Changing an array in place using splice() JavaScript
- Add a scalar value with each element of a masked Array in-place in Numpy
- Subtract a scalar value from each element of a Masked Array in-place in Numpy
- Multiply each element of a masked Array by a scalar value in-place in Numpy

Advertisements