เราจำเป็นต้องเขียนฟังก์ชัน 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 ]