"Whale Talk" revisited with built-in methods

After learning about built-in methods and higher order functions, I decided to go back and visit the Whale Talk project.

Instead of using nested for loops, I wanted to use some of the objects on the MDN website in order to make the code cleaner and simpler.

As per the instructions, I was able to use the .filter and .includes methods to compare the two arrays and pull out the vowels from the input array. Nevertheless, I’m having trouble figuring out how I would, in a similar manner, double all the “e’s” and “u’s”, as the directions suggest. Could I embed an if statement within the .filter object? Would .map be better?

Here’s my code so far:

const input = 'everyone is itchy all around us';
const vowels = ['a', 'e', 'i', 'o', 'u'];

const inputArray = [...input];
//console.log(inputArray);

function findCommonElements(arr1, arr2) { 
    let result = arr1.filter(x => arr2.includes(x));
    return result;
}; 


console.log(findCommonElements(inputArray, vowels)); // logs: [ 'e', 'e', 'o', 'e', 'i', 'i', 'a', 'a', 'o', 'u', 'u' ]

Perhaps there is another prototype method that you could use as part of your code? :slight_smile:

1 Like

Realize this is ancient but I wanted to take it to the extreme to showcase the power (and fun) of the functional methods:

//const input = 'turpentine and turtles';
//const input = 'Hi, Human';
const input = 'a whale of a deal!';

const vowels = "aeiou";

const result = 
  input.toLowerCase()
        .split('')
        .filter(c => vowels.includes(c))
        .map(c => c == 'e' || c == 'u' ? c + c : c)
        .join('')
        .toUpperCase();

console.log(result);
// => AAEEOAEEA