我目前正在终端/控制台上学习 javascript 排序,由于我的经验有限,我在解决这个问题上遇到了困难......所以请跟我一起。
我正在创建一个函数,它将返回一个包含字符串元音的数组。结果数组的元素按先出现的字符排序。例如:
假设我有这个字符串=“示例案例”
该函数应返回一个结果数组,如下所示 = [a,a,e,e]
下面是我的代码,现在我能做的就是用我的函数提取元音:
const prompt = require('prompt-sync')();
const isVowel = (c) => {
if(c) {
return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1;
} else {
return 'string is empty';
}
};
const sortChar = () => {
const wordsInput = prompt("Input one line of word(s): ");
let vowels = wordsInput.split(' ').join('').split('').filter((x) => isVowel(x));
let consonants = wordsInput.split(' ').join('').split('').filter((x) => !isVowel(x));
console.log(vowels.sort((a, b) => {
if(a === b) {
return 1;
}
return 0;
}))
};
sortChar();
上述代码的当前输出:[a,e,a,e]
如何对这个结果数组进行排序,使得新结果为 [a,a,e,e]?
如有任何意见,我们将不胜感激,提前谢谢您!
你可以
vowels
,function orderVowels(string) {
const
indices = {},
vowels = [];
for (const v of string.match(/[aeiou]/ig)) {
if (!(v in indices)) {
indices[v] = vowels.length;
vowels.push([]);
}
vowels[indices[v]].push(v);
}
return vowels.flat();
}
console.log(orderVowels("Sample Case"));
对我来说,对于这个特定的用例来说,排序是一种过于“昂贵”的操作。我宁愿将其视为过滤掉元音并按出现顺序注意:如果您要查找的不是按词法排序元音(按字母顺序)而是按出现顺序排序,则
localeCompare()
似乎不是合适的工具。如果我错过了整个要点,您可以放心地忽略这个答案。
堆叠它们(其中Map
可能会派上用场)。
const sourceString = 'Sample Case'
const isVowel = char =>
'aeiouAEIOU'.includes(char)
const stackFilteredVowels = str => {
const vowelsMap = [...str.toLowerCase()]
.reduce((acc, char) => {
const isCharVowel = isVowel(char)
if(isCharVowel) {
const vowelOccurence = acc.get(char)
acc.set(char, (vowelOccurence ?? 0)+1)
}
return acc
}, new Map)
const stackedVowels = [...vowelsMap.entries()]
.reduce((acc, [vowel, occurence]) =>
(acc.push(...Array(occurence).fill(vowel)), acc), [])
return stackedVowels
}
console.log(stackFilteredVowels(sourceString))
.as-console-wrapper{min-height: 100%;}
const isVowel = (c) => !c ? 'string is empty' : ['a', 'e', 'i', 'o', 'u'].includes(c);
const sortChar = () => {
const wordsInput = "Input one line of word(s): ";
const vowels = [...wordsInput].filter(char => isVowel(char) && char.match(/\w/));
const consonants = [...wordsInput].filter(char => !isVowel(char) && char.match(/\w/));
console.log({
vowelsSorted: vowels.sort((a, b) => new Intl.Collator('en').compare(a, b)),
consonantsSorted: consonants.sort((a, b) => new Intl.Collator('en').compare(a, b))
})
}
;
sortChar();
isVowel
过滤辅音。使用 localeCompare
const isVowel = c => `aeiou`.indexOf((c || ``).toLowerCase()) > -1;
// ^ use empty string if !c
const sortChar = words => {
return [...words].filter( chr => isVowel(chr) )
// ^ spread into array
// ^ filter delivers array
.sort( (a, b) => a.localeCompare(b) )
// ^ sort using localeCompare
.join(``);
};
console.log(sortChar(`As said: input one line of word(s)`));