anubysh
anubysh

Reputation: 586

Sorting an array of strings with custom ordering

When you sort an array lets say:

const arr = ["bad", "good", "all", "ugly"]

with arr.sort() the response tends to be:

arr = ["all", "bad", "good", "ugly"]

but what if I need custom ordering such as:

arr = ["bad", "good", "ugly", "all"]

ie for the sake of the example you need to push the "all" element to the end of the sorted array instead of the start

What I did was to sort the array and then removed the "all" element from the array only to add it in the end ie

const a = _.pull(arr, "all");
a.splice(3, 0, "all")
console.log(a)     // ["bad", "good", "ugly", "all"]

Is there a better or a less complex way of doing the same?

Upvotes: 0

Views: 780

Answers (3)

mbojko
mbojko

Reputation: 14679

You can use custom comparator for sorting. Something like

[...arr].sort((x, y) => x === 'all' ? 1 : y === 'all' ? -1 : x.localeCompare(y))

const arr = ["bad", "good", "all", "ugly"];
console.log([...arr].sort((x, y) => x === 'all' ? 1 : y === 'all' ? -1 : x.localeCompare(y)))

Upvotes: 6

pravin kumar
pravin kumar

Reputation: 1

i think below one is the idle one. Because while sorting itself you can pull the "all" to the end

let list = ["all", "bad", "good", "ugly"]
list.sort((a, b) => {
    if(a === 'all') {return 1;}
    if(b === 'all') {return -1;}
    if(a < b) { return -1; }
    if(a > b) { return 1; }
    return 0
})
console.log(list)

Upvotes: 0

adiga
adiga

Reputation: 35222

You could do something like this using the OR operator:

let arr = ["all", "bad", "all", "good", "ugly"]

arr.sort((a, b) => (a == "all") - (b == "all") || a.localeCompare(b))

console.log(arr)

Subtracting booleans returns a number (true - false === 1). If one the strings is "all", it won't check the second condition at all.

Upvotes: 0

Related Questions