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);
[ 'None', 'Apple', 'Dates', 'Grapes', 'Orange', 'Pineapple' ]

How It Works

The sorting function uses a clever comparison technique:

  • (b === text) - (a === text) returns 1 if b matches the default value, -1 if a matches, or 0 if neither matches
  • This ensures the default element comes first
  • a.localeCompare(b) handles alphabetical sorting for the remaining elements

Alternative Approach: Using Filter and Concat

const arr2 = ["Banana", "Cherry", "Apple", "Default", "Berry"];

const sortWithDefault = (array, defaultValue) => {
    const defaultItems = array.filter(item => item === defaultValue);
    const otherItems = array.filter(item => item !== defaultValue).sort();
    return defaultItems.concat(otherItems);
};

const result = sortWithDefault(arr2, "Default");
console.log(result);
[ 'Default', 'Apple', 'Banana', 'Berry', 'Cherry' ]

Handling Multiple Default Values

const fruits = ["Apple", "None", "Orange", "None", "Grapes"];

const sortWithMultipleDefaults = (arr, defaultVal) => {
    return arr.sort((a, b) => {
        if (a === defaultVal && b !== defaultVal) return -1;
        if (b === defaultVal && a !== defaultVal) return 1;
        return a.localeCompare(b);
    });
};

console.log(sortWithMultipleDefaults([...fruits], "None"));
[ 'None', 'None', 'Apple', 'Grapes', 'Orange' ]

Conclusion

Use the comparison function approach for in-place sorting, or the filter-concat method for functional programming style. Both effectively place your default element first while maintaining alphabetical order for remaining items.

Updated on: 2026-03-15T23:19:00+05:30

411 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements