- 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
Order items alphabetically apart from certain words JavaScript
Let’s say, we have two arrays both containing String literals, one of which is required to sort alphabetically, but if this array, the one we have to sort contains some words from the other array, those words should appear at the very top and the rest of the element should be sorted alphabetically.
Let’s write a function, say excludeSorting(arr, ex) where arr is the array to be sorted and ex is the array of strings that should appear at top in arr (if they appear in arr).
Example
const arr = ['apple', 'cat', 'zebra', 'umbrella', 'disco', 'ball', 'lemon', 'kite', 'jack', 'nathan']; const toBeExcluded = ['disco', 'zebra', 'umbrella', 'nathan']; const excludeSort = (arr, ex) => { arr.sort((a, b) => { if(ex.includes(a)){ return -1; }else if(ex.includes(b)){ return 1; } return a > b ? 1 : -1 }); }; excludeSort(arr, toBeExcluded); console.log(arr);
Output
The output in the console will be −
[ 'nathan', 'disco', 'umbrella', 'zebra', 'apple', 'ball', 'cat', 'jack', 'kite', 'lemon' ]
Advertisements