Order items alphabetically apart from certain words JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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'
]
Published on 21-Aug-2020 18:34:36