字符串中最接近的元音的距离-JavaScript
我们需要编写一个JavaScript函数,该函数接收带有至少一个元音的字符串,并且对于字符串中的每个字符,我们都必须在字符串中映射一个数字以表示其与元音的最接近距离。
例如:如果字符串是-
const str = 'vatghvf';
那么输出应该是-
const output = [1, 0, 1, 2, 3, 4, 5];
示例
以下是代码-
const str = 'vatghvf';
const nearest = (arr = [], el) => arr.reduce((acc, val) => Math.min(acc,
Math.abs(val - el)), Infinity);
const vowelNearestDistance = (str = '') => {
const s = str.toLowerCase();
const vowelIndex = [];
for(let i = 0; i < s.length; i++){
if(s[i] === 'a' || s[i] === 'e' || s[i] === 'i' || s[i] === 'o' ||
s[i] === 'u'){
vowelIndex.push(i);
};
};
return s.split('').map((el, ind) => nearest(vowelIndex, ind));
};
console.log(vowelNearestDistance(str));输出结果
以下是控制台中的输出-
[ 1, 0, 1, 2, 3, 4, 5 ]
热门推荐
10 儿子立冬祝福语简短独特
11 对当兵的祝福语简短
12 侄儿高考试祝福语简短
13 伴郎红包祝福语朋友简短
14 媳妇生日简短祝福语朋友
15 公司年会祝福语简短最好
16 元旦感恩祝福语简短大全
17 红包祝福语简短10字
18 周六早晨祝福语简短