0

I need help with making a function which I need to sort array of users names by a given value + alphabet. First I need to see the names starting with my value(also sorted by alphabet) and then the rest of the array sorted by alphabet.

For example:

const users = ["orel","or","boris","rory","dorel","conor","coral"];

value: "or"

the output I expect:

//users ["or","orel","boris","conor","coral","dorel","rory"]

I could manage which making the alphabet sorting but got stuck combining it with sorting by the given value. thanks by heart!

1 Answer 1

1

You can use this callback function to sort:

const users = ["orel","or","boris","rory","dorel","conor","coral"];
const value = "or";

users.sort((a,b) => b.startsWith(value) - a.startsWith(value) || a.localeCompare(b));

console.log(users);

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

6 Comments

whats is localCompare? @trincot
localeCompare: it gives -1, 0, or 1 depending on how the strings a and b compare alphabetically.
so in the sort method above what is the exact logic? because as far as I know startsWith returns true or false right? @trincot
Yes that's right, but the minus operator will convert that to 0 or 1 and then do the subtraction. So the subtraction can give -1, 0 or 1. If 0, they either both start with "or", or both do not start with "or". If that happens the localeCompare determines the order. If the first subtraction gives a non-zero result, that determines the order (localeCompare is not executed).
That is the principle of short-circuit evaluation: JavaScript reasons that if the first expression in a logical OR (||) is truthy (in this case 1 or -1), there is no gain to still evaluate the other half of the logical expression, as it is already clear that the outcome of the logical expression cannot be falsy. And so JavaScript determines that the whole expression evaluates to the value of the first part (1 or -1) without evaluating the other half.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.