I want to write a function that sorts a bunch of words by the number of character “a”s within the word (decreasing order). If some words contain the same amount of character “a”s then you need to sort those words by their lengths.
Input :
["aaaasd", "a", "aab", "aaabcd", "ef", "cssssssd", "fdz", "kf",
"zc", "lklklklklklklklkl", "l"]
Output :
["aaaasd", "aaabcd", "aab", "a", "lklklklklklklklkl", "cssssssd",
"fdz", "ef", "kf", "zc", "l"]
I have tried finding the answers but nothing is very specific.
CodePudding user response:
The builtin array#sort
method can be used with a custom comparator function. Here's an exmaple that behaves the way you described.
const dat = ["aaaasd", "a", "aab", "aaabcd", "ef", "cssssssd", "fdz", "kf",
"zc", "lklklklklklklklkl", "l"]
function sortByAs(arr) {
return arr.sort((a, b) => {
const diff = numberOfAs(b) - numberOfAs(a);
// different #s of A, return the comparison
if (diff !== 0) return diff;
// fallback to length comparison
return b.length - a.length;
});
}
function numberOfAs(str) {
const matches = str.match(/a/g) || [];
return matches.length;
}
console.log(sortByAs(dat));