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!
Jonathan Hall
80.5k19 gold badges163 silver badges207 bronze badges
1 Answer 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);
answered Dec 9, 2019 at 21:08
trincot
357k38 gold badges282 silver badges340 bronze badges
Sign up to request clarification or add additional context in comments.
6 Comments
rio
whats is localCompare? @trincot
trincot
rio
so in the sort method above what is the exact logic? because as far as I know startsWith returns true or false right? @trincot
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).trincot
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. |
lang-js