Order items alphabetically apart from certain words JavaScript

In JavaScript, you can sort an array alphabetically while keeping certain priority words at the top. This is useful when you need specific items to appear first, regardless of alphabetical order.

Let's create a function excludeSort(arr, ex) where arr is the array to be sorted and ex contains the priority words that should appear at the top.

How It Works

The sorting logic uses a custom comparator that:

  • Places priority words (from ex array) at the top
  • Sorts remaining words alphabetically
  • Uses Array.includes() to check if a word is in the priority list

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);
[
  'nathan', 'disco',
  'umbrella', 'zebra',
  'apple', 'ball',
  'cat', 'jack',
  'kite', 'lemon'
]

Improved Version with Preserved Order

To maintain the original order of priority words and sort only the remaining items:

const arr2 = ['apple', 'cat', 'zebra', 'umbrella', 'disco', 'ball',
'lemon', 'kite', 'jack', 'nathan'];
const priority = ['disco', 'zebra', 'umbrella', 'nathan'];

const improvedSort = (arr, priorityWords) => {
    const priorityItems = arr.filter(item => priorityWords.includes(item));
    const regularItems = arr.filter(item => !priorityWords.includes(item)).sort();
    
    return [...priorityItems, ...regularItems];
};

const result = improvedSort(arr2, priority);
console.log(result);
[
  'zebra', 'umbrella',
  'disco', 'nathan',
  'apple', 'ball',
  'cat', 'jack',
  'kite', 'lemon'

Key Points

  • Use negative return values (-1) to place items earlier in the sorted array
  • The includes() method efficiently checks priority word membership
  • Regular alphabetical sorting applies to non-priority items
  • The improved version preserves the original order of priority items

Conclusion

Custom sorting with priority words combines conditional logic with alphabetical ordering. Use Array.sort() with a custom comparator or separate filtering for more control over the final arrangement.

Updated on: 2026-03-15T23:18:59+05:30

181 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements