

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 Questions & Answers
- 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
- Use array as sort order in JavaScript
- How to delete a particular element from a JavaScript array?
- Present date as default value in a table
- Changing an array in place using splice() JavaScript
- JavaScript: How to check whether an array includes a particular value or not?
- Write a program to find the index of particular element in an array in javascript?
- Sort the masked array in-place in NumPy
- 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
- Finding place value of a number in JavaScript
- True Divide each element of a masked Array by a scalar value in-place in Numpy
Advertisements