Checking for vowels in array of numbers using JavaScript

We are required to write a JavaScript function that takes in an array of numbers. If in that array there exists any number which is the char code of any vowel in ASCII, we should switch that number to the corresponding vowel and return the new array.

Understanding ASCII Character Codes

In ASCII, vowels have specific character codes:

  • 'a' = 97
  • 'e' = 101
  • 'i' = 105
  • 'o' = 111
  • 'u' = 117

Example

Let's create a function that converts ASCII codes to vowels when they match:

const arr = [5, 23, 67, 101, 56, 111];

const changeVowel = (arr = []) => {
    for (let i = 0, l = arr.length; i < l; ++i) {
        let char = String.fromCharCode(arr[i]);
        if ('aeiou'.indexOf(char) !== -1) {
            arr[i] = char;
        }
    }
    return arr;
};

console.log(changeVowel(arr));
[ 5, 23, 67, 'e', 56, 'o' ]

How It Works

The function works by:

  1. Converting each number to its ASCII character using String.fromCharCode()
  2. Checking if the character is a vowel using indexOf()
  3. Replacing the number with the vowel character if found
  4. Returning the modified array

Alternative Implementation

Here's a cleaner version using map() and explicit vowel checking:

const arr2 = [97, 98, 101, 105, 111, 117, 120];

const changeVowelMap = (arr = []) => {
    const vowels = ['a', 'e', 'i', 'o', 'u'];
    
    return arr.map(num => {
        const char = String.fromCharCode(num);
        return vowels.includes(char) ? char : num;
    });
};

console.log(changeVowelMap(arr2));
[ 'a', 98, 'e', 'i', 'o', 'u', 120 ]

Conclusion

This approach effectively converts ASCII character codes to their corresponding vowel characters when they match. The function preserves non-vowel numbers while replacing vowel codes with actual vowel characters.

Updated on: 2026-03-15T23:19:00+05:30

281 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements