Fullstack Software Engineer
In this tutorial we will learn few basic problem solving using javascript build in functions of string, array, etc.
This is the most favourite question of interviewers to reverse a string. Well you can solve it in different ways:
Solution 1: Using built in function
Built in functions used:
String.split() : Divides a string into substrings with the separator passed and converts into an array,
Array.reverse() : Reverses the elements of an array,
Array.join() : Creates and returns a new concatenated string of all the elements in the array specified by a string separator.
function stringReverse(str){
return str.split('') // split each character of the string and return array of characters
.reverse() // reverse the array of characters
.join(''); // join the array into string again
}
Solution 2:
Now the interviewer says don't use the reverse() function !! Now what ??
No worries, we have for loop for the rescue, here is how you can use it
function stringReverse(str){
let reverseString = '';
for(let i = str.length - 1; i >= 0; i--) {
reverseString = reverseString + str[i];
}
return reverseString;
}
Solution 3: Solve it smarter
Show your smartness that you know the latest javascript patterns and use reduce
Reduce is a function that executes on each element in the array and results in a single output. It takes two parameters - first: a reducer function to execute on each array element and second - an initial value
function stringReverse(str){
return str.split('')
.reduce((reverseString, character) => character + reverseString, '');
}
Out of the 26 alphabets in english 5 of them are considered as vowels: A, E, I, O, U. (Bonus knowledge : Y is considered as a sixth vowel. One vowel can have many sounds and sometimes can be silent without any sound at all).
Solution 1: Using a old school for loop (Understand the concept)
function countVowels(str){
const vowels = ['a','e','i','o','u']
let count = 0;
for(let i=0; i<str.length; i++){
if(vowels.indexOf(str[i]) != -1){
count++;
}
}
return count;
}
Solution 2: Using for of loop (Build upon your fundamental and apply latest trends to get smarter)
function countVowels(str){
const vowels = ['a','e','i','o','u']
let count = 0;
for(let element of str){
if(vowels.indexOf(element) != -1){
count++;
}
}
return count;
}
1 Comments
Very helpful blog, and very informative
yes