0

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?

2
  • 1
    is there any reason for not redeclaring the array? it seems a static array so, unless you need to work on dynamic arrays, you could just redeclare it. I wouldn't even call such a "sorting", this is rather moving an item to the end of the array. Commented Apr 9, 2019 at 10:25
  • please add which order do you need. actually it looks like you want to have a fixed order of the items. Commented Apr 9, 2019 at 11:35

3 Answers 3

6

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)))

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.