Tuesday, July 20, 2021

Junior Developer Central JS Practice Exercise - 22

 
Question: 

Write a Javascript function that accepts a string as a parameter and counts the number of vowels within the string. 




Answer: 

function vowelCount (str) {

  let vowels = /[aeiou]/gi;
  let result = str.match(vowels);
  let count = result.length;
  return count; 
  
  };




> we declare a function 'vowelCount' 
> it has one parameter 'str', which is a string
> we declare a variable 'vowels' and initialize it with the 5 vowels
> the 'g' modifier is used on the 'vowels' variable to perform a global match 
> a global match will find all matches and will not stop after finding the first match
additionally  the 'i' modifier is used on the 'vowels' variable to perform case insensitive matching
> we declare another variable 'result' and initialize it with the result we get when we use the match () method on the 'str' parameter
> the match() method searches a string for a match against a regular expression and returns the matches as an array object
> we want to match the 'str' with the elements in the 'vowels' variable and store the results in the 'result' array
> we declare another variable 'count' and initialize it with a value we get by using the length property on the array 'result' which will give us the total number of elements in the 'result' array
> we return the 'count' variable

Monday, July 19, 2021

Junior Developer Central JS Practice Exercise - 21

 
Question: 

Write a Javascript function that returns a passed string with letters in alphabetical order. 

Example String:           'javascript' 
Example Output:          'aacijprstv'




Answer: 

function alphaStr (str) {

return str.split('').sort().join('')

}          




> we declare a function 'alphaStr' 
> it has one parameter 'str' 
> we use the split ('') method on the string 'str' to split all the characters in an array
> we then use the sort() method to sort the characters in alphabetical order
> we then use the join('') method to create a string by concatenating all the sorted elements of the array created 
> we return this line of code to get our alphabetically sorted string

Junior Developer Central JS Practice Exercise - 20

 
Question: 

Write a Javascript function that returns true if the provided predicate function returns true for all elements in a collection, false otherwise. 




Answer: 

function checkFunction(arr, fn) {
  for (let i = 0; i < arr.length; i++) {

    if (!fn(arr[i])) {
      return false;
    }

  }
  return true;
}




> we declare a function 'checkFunction' 
> it has two parameters 'arr' & 'fn' 
> we want to return false if 'fn' (which is a function) returns false for even one element in 'arr' (which is an array)
> our function should return true if the function 'fn' returns true for all elements in array 'arr'
> so in order to check the result of the function 'fn' on each and every element of array 'arr' we use the for loop
>  we additionally use the if statement to check the boolean value on each iteration of the for loop
> we return false if the condition is met and the loop is terminated
> we keep the iterations running till all the elements of the array are checked and terminate the loop by returning 'true'

Junior Developer Central JS Practice Exercise - 19

 
Question: 

Write a Javascript program to generate a random hexadecimal color code




Answer: 

function getRandomColor() {
        
        let letters = '0123456789ABCDEF'.split('');
        let color = '#';
        for (var i = 0; i < 6; i++ ) {
            color += letters[Math.round(Math.random() * 15)];
        }
        return color;
    }




> we declare a function 'getRandomColor' 
> it has no parameters
> we create a variable 'letters' 
> it is a string of 16 characters - '0123456789ABCDEF'
> we use the split () method to return an array with 16 array elements
> we declare another variable 'color' 
> its is a string with only the '#' character
> we then create a for loop 
>> initialization - before the loop starts we set our variable i = 0
>> condition - we define the condition for the loop to run ('i' must be less than 6)
>> final expression - at the end of each loop iteration we increment the counter variable
>> understanding the statement in the for loop
>> we want to generate a 6 digit hexadecimal color code with a '#' sign before it
>> that 6 digit hexadecimal code needs to be taken from the array we created 'letters' 
>> we use Math.random() to randomly select any of the 16 array elements
>> since array indexes start from 0, we want a random index number from 0 to 15
>> we use the Math.round() method with Math.random() to get a number with no decimals
>> we use both these methods to select a random index number from the 'letters' array
> we then concatenate the result of the 'for loop iteration' with the 'color' string variable
> the for loop will terminate after the 5th iteration and return the 'color' variable

Sunday, July 18, 2021

Junior Developer Central JS Practice Exercise - 18

 
Question: 

Write a Javascript program to convert a comma-separated values (CSV) string to a 2D array. A new line indicates a new row in the array. 

for eg. 

Input: 

const oldString = `abc,def,ghi
jkl, mno, pqr
stu, vwx, yza`;

Output: 

0: (3) ["abc", " def", " ghi"]
1: (3) ["jkl", " mno", " pqr"]
2: (3) ["stu", " vwx", " yza"]




Answer: 

function createArr(str) {

  return str.split('\n').map(row => row.split(','));

}




> we declare a variable 'createArr' 
> it has one parameter 'str' 
> to explain this function, we shall use the input example in the question above 'oldString'
> we first split the 'str' with the split () method that will return an array of substrings
> the split ('\n') method will return a new array which will have three items 
> each of these items is a row from the 'oldString' mentioned above
>> so after split ('\n) we get 
>> 0: ["abc, def, ghi"]
>> 1: ["jkl, mno, pqr"]
>> 2: ["stu, vwx, yza"]
> but we need a 2 dimensional array 
> so we need to split each of the values, in the row, into an array itself
>> like this: 
>> 0: ["abc", " def", " ghi"]
>> 1: ["jkl", " mno", " pqr"]
>> 2: ["stu", " vwx", " yza"]
> in order to further split each of the values into an array itself we use the map() method
> the map() method creates a new array with the results of calling a function for every array element
> the map() method calls the provided function once for each element in an array 
> our aim is to further split the row elements we have, into an array itself 
> so we use the map () method and call a function, that will be called on each value of the 'row' 
> so we will use the split () method on each values of the 'row' and split them by the 'comma'
> like this .map(row => row.split(',')
> this will be a one line code and we shall return the same

Thursday, July 15, 2021

Junior Developer Central JS Practice Exercise - 17

 
Question: 

Write a Javascript program to compare two objects to determine if the first one contains the same properties as the second one (which may also have additional properties)

for eg: 

const objA = { a: 1, b: 2, c: 1 }; 
const objB = { a: 1, b: 1, c: 1 };
const objC = { a: 1, b: 1, d: 1 };




Answer: 

function comTwoObj (obj1, obj2) {

const obj2Keys = Object.keys(obj2); 
return Object.keys(obj1).every(key => obj2Keys.includes(key));

}




> we declare a function 'comTwoObj' 
> it has 2 parameters 'obj1' & 'obj2' 
> we want to compare the keys of the two objects 'obj1' & 'obj2' 
> we do not want to compare the values, only the keys
> in our case the 'keys' are: a, b, c & so on
> we want to check if 'obj2' has all the keys of 'obj1' 
> 'obj2' can have additional keys as well, for eg: a, b, c, d, e & so on
> but it should have all the keys of 'obj1' 
> so first we create a variable 'obj2Keys' 
> we initialize it with a value we get by using the Object.keys() method on 'obj2'
> Object.keys() will return an array of a given object's property names or key names
> so our variable 'obj2Keys' will be an array of key names / property names of 'obj2'
> we then want to return true, if 'obj2Keys' includes all the key names of 'obj1' 
> however we cannot compare 'obj2Keys' to 'obj1' as 'obj2Keys' is an array
> so we use the Object.keys() method on 'obj1' as well 
> this method will return an array
> we also add the every() method on Object.keys(obj1)
> like this: Object.keys(obj1).every()
> the every() method returns true if all elements in an array pass a test
> the every method () executes the function once for each element present in the array
> so within the every () method we want to check if the array 'obj2Keys' includes all the elements in the array that is created [ when we use the '' Object.keys(obj1) '' ]
> so we use the includes() method to compare and check the two arrays
> this test will return 'true' if all elements of the array 'Object.keys(obj1) are included in 'obj2Keys'

Junior Developer Central JS Practice Exercise - 16

 
Question: 

Given a year, report if it is a leap year. 




Answer: 

function isLeapYear (year) {

const leapYear01 = year; 
const leapYear02 = leapYear01 / 4;

if (Number.isInteger(leapYear02)) {
return true; 
} else { 
return false;
}
}




> we declare a function 'isLeapYear' 
> it has one parameter 'year' 
> leap year has 366 days
> leap year comes every 4 years
> all leap years are divisible by 4
> hence all the years that are divisible by 4 are 'leap years' 
> so first we create a variable 'leapYear01' 
> we initialize it with a value that we get in 'year' argument
> then we create another variable 'leapYear02' 
we initialize it with a value that we get by dividing the 'leapYear01' by 4
> we then open an if/else statement
> we want to check if the value stored in 'leapYear02' is an integer
> an integer is a whole number
> an integer is a number that can be written without a fractional component
> our if statement will check if the value is an integer
> if it is an integer, then we want to return true
> if it is not an integer, then we want to return false
> we return false as the value stored is not a whole number and so the value stored in 'leapYear02' is not divisible by 4
> if it is not divisible by 4 then it is not a 'leap year' 

Monday, July 12, 2021

Junior Developer Central JS Practice Exercise - 15

 
Question: 

Write a Javascript program to replace the first digit in a string with $ character. 




Answer: 

function replaceFirstDigit (str) {
const newStr = str.replace(/[0-9]/, '$'); 
console.log (newStr); 
}




> we declare a function 'replaceFirstDigit' 
> it has one parameter 'str' which is a string
> we need to replace only the first digit occurrence in the 'str' string with a '$' sign 
> we declare a variable 'newStr' 
> we initialize it with a value that we get by using the replace method on 'str' 
> we use the character class or ''RegExp [0-9] Expression'' to find the digit in 'str' 
> we do not use the modifier 'g' as it will search for all the digits
> we only want the first occurrence so we will use on '/[0-9]/' & not '/[0-9]/g'
> we use '$' sign as the replacement
> we then console.log the 'newStr' variable to get our answer

Junior Developer Central JS Practice Exercise - 14

 
Question: 

Write a Javascript program to get the largest even number from an array of integers. 




Answer: 

function largestEven (arr) {
const newArr01 = arr; 
const newArr02 = newArr01.filter(i => i % 2 === 0); 
newArr02.sort((a,b) => b - a); 
console.log (newArr02[0]); 
}




> we declare a function 'largestEven' 
> it has one parameter 'arr' which is an array of numbers
> we create a variable 'newArr01' and initialize it with value of the 'arr'
> we create another variable 'newArr02' 
> we initialize it with a value we get by using the filter method & modulo of 2, on 'newArr01'
> we then sort the 'newArr02' variable in descending order
> we console.log the first index value of the 'newArr02' to get the largest even number

Junior Developer Central JS Practice Exercise - 13

 
Question: 

Write a Javascript program to check whether a given array of integers is sorted in ascending order. 




Answer: 

function isAscendingOrder (arr) {

for (let i = 0; i < arr.length; i++) {

if (arr[i+1] < arr[i]) return false;

} return true;

}



> we declare a function 'isAscending' 
> it has one parameter 'arr', which is an array of integers
> we have to check if this array of integers is sorted in ascending order or not
> so we use the for loop to check if each integer is greater than the following integer
> the for loop ensures that our check begins from the first integer to the last
> if the integer is greater than the following integer we return 'false' 
> because an array of ascending numbers, will have the preceding number lesser than the following number
> if that is not the case then we return 'true' once the for loop has finished the iteration and not found any number in the array which is greater than its following integer

Junior Developer Central JS Practice Exercise - 12

 
Question: 

Write a Javascript program to find the number of even values up to a given number. 




Answer: 

function evenValue (num) {

let evenNum = num;
let allVal = []; 
let totalEven; 

for (let i = 1; i < evenNum; i++) {

allVal.push(i);
totalEven = allVal.filter(i => i % 2 === 0).length;

}; 
console.log(totalEven);
}




> we declare a function 'evenValue'
> it has one parameter 'num'; which is a number
> we have to find out all the even values up to the number provided in 'num' 
> so first we create an array of all numbers from 1 to n (or 'num')  
>> we declare a variable 'allVal' which is an array
>> we use a for loop to push all the numbers up to n (or 'num')
> secondly we use the filter method on 'allVal' to create an array of even numbers
>> we declare another variable 'totalEven' 
>> it is initialized with a value we get by using the filter method on 'allVal' 
>> in order to get the even numbers, we use the modulo operator 
>> if the number is even then the remainder will always be '0' if number is divided by 2
>> since we do not need an array of even numbers but we only need the total number of even digits, we use the length method after the filter method on 'allVal' 
>> so 'totalEven' will have the total number of even digits
> we console.log it to get our answer

Junior Developer Central JS Practice Exercise - 11

 
Question: 

Write a Javascript program to find the number of even digits in an array of integers. 




Answer: 

function evenArr (arr) {

let regArr = arr; 
let evenArrL = regArr.filter(i => i % 2 === 0).length; 
console.log(evenArrL); 

}




> we declare a function 'evenArr' 
> it has one parameter 'arr' 
> we create a variable 'regArr'
> it is initialized with the parameter 'arr' which is an array of integers
> we create another variable 'evenArrL'
> we initialize it with the value we get when we use the filter method on 'regArr' 
> we want to filter all the even numbers of the 'regArr' 
> to do that we use the modulo / remainder operator 
> however we only need to know the number of even digits 
> so we add the 'length' method to get the total number of even digits in the array
> finally we console.log our answer

Sunday, July 11, 2021

Junior Developer Central JS Practice Exercise - 10

 
Question: 

Write a Javascript program to check if a given string contains 2 to 4 occurrences of a specified character. 




Answer: 

function countChar (str, char) {

let arr01 = str.split(''); 
let arr02 = arr01.filter(ch => ch === char).length; 

if (arr02 >= 2 && arr02 <= 4) {
return true; 
} else {
return false;
}
}




> we declare a function 'countChar' 
> it has 2 parameters 'str' & 'char'
> we create a variable 'arr01' & initialize it with a value we get by splitting the 'str' 
> 'arr01' is an array as we have split the 'str' elements into an array of characters
> we create another variable 'arr02' and use the filter method on 'arr01' 
> we want to filter out all the elements that are equal to the character we need to find
> however we do not need an array of all the similar characters 
> we need to know only the number of times it has occurred in the string
> so after using the filter method to find the number of occurrences, we add the length method
> so 'arr02' will be initialized with the number of occurrences
> we then open if/else statements to check two conditions
> if 'arr02' is greater than equal to 2, and if 'arr02' is lesser than equal to 4
> if it is true then we return 'true' 
> if it is false then we return 'false'

Junior Developer Central JS Practice Exercise - 09

 
Question: 

Given two values, write a Javascript program to find out which one is nearest to 100. 




Answer: 

function nearHund (num1, num2) {

if (num1 > num2 && num1 <= 100) {

return num1; 

} else if (num1 < num2 && num2 <= 100) {

return num2; 

} else if (num1 > num2 && num2 > 100) {

return num2; 

} else if (num1 < num2 && num1 > 100) {

return num1;

} else {

return num1;

}

}




> we declare a function 'nearHund'
> it has two parameters 'num1' and 'num2'
> we open if / else statements to check if the numbers are near the number '100' 
> there are mainly 5 possibilities that need to be checked
>> first is to check if 'num1' is greater than 'num2' and 'num1' is less than or equal to 100
>>> if this condition is true then we want to return 'num1'
>> second is to check if 'num2' is greater than 'num1' and 'num2' is less than or equal to 100
>>> if this condition is true then we want to return 'num2'
>> third is to check if 'num1' is greater than 'num2' and 'num2' is more than or equal to 100 
>>> if this condition is true then we want to return 'num2'
>> fourth is to check if 'num2' is greater than 'num1' and 'num1' is more than or equal to 100
>>> if this condition is true then we want to return 'num1'
>> fifth and the easiest one is to check if both 'num1' & 'num2' are same
>>> if this condition is true then we want to return any parameter 'num1' or 'num2'

Junior Developer Central JS Practice Exercise - 08

 
Question: 

Write a Javascript program to concatenate two strings except their first character. 




Answer: 

function concatStr (str01, str02) {
return str01.slice(1) + str02.slice(1);
}




> we declare a function 'concatStr'
> it has two parameters 'str01' & 'str02' 
> we simply return the concatenated value of the slice method used on 'str01' & 'str02' 
> we need to remove the first character from both the string inputs 'str01' & 'str02' 
> so we want the slice to begin from the second character onwards
> thus we use 1 as the start parameter as the first character has the position of 0

Junior Developer Central JS Practice Exercise - 07

 
Question: 

Write a Javascript program to extract the first half of a string of even length. 




Answer: 

function extHalf (str) {

let str001 = str; 
if (str001.length % 2 === 0) { 
return str001.slice(0, str001.length/2); 
} else {
return str001
}
}




> we declare a function 'extHalf'
> it has one parameter 'str'
> we create a variable 'str001'
> we initialize it with a value of our argument 'str' 
> we then open if/else statements to check if the length of 'str001' is even
> we use the modulo / remainder operator to check if the length is even
> if it is even then the modulo operator would have '0' as remainder
> if it is odd then the modulo operator would have '1' as remainder
> if 'str001' is even then we want to return the first half 
> we do that by using the slice method on 'str001' 
> our start parameter is 0 as we want to slice the first half
> we use str001.length / 2, which will give us the half of the total length of the string
> so our end parameter is the half of the total length of the string
> if 'str001' is an odd number then we want to return the same string without any extraction

Junior Developer Central JS Practice Exercise - 06

 
Question: 

Write a Javascript program to create a new string from a given string taking the first 3 characters and the last 3 characters of a string 'and adding them together. The string length must be 3 or more, if not, the original string is returned. 





Answer: 

function stringFormat (str) {

let str001 = str; 
if (str001.length < 3) {
return str001; 
} else {
let str002 = str001.slice(0, 3); 
let str003 = str001.slice(-3); 
let finalString = str002+str003; 
console.log(finalString);
}




> we declare a function 'stringFormat' 
> it has one parameter 'str' 
> we create a variable str001 and initialize it with the argument 'str'
> we then open an if/else statement to check if the length of the 'str001' is less than 3
> if it is less than 3 then we want the function to return the 'str001' variable 
> if it is 3 or more than 3 then we slice the str001 twice 
>> our first slice is saved in variable 'str002' and slices the first 3 characters of the string
>> our second slice is saved in variable 'str003' and slices the last 3 characters of the string
> we then create another variable 'finalString' 
> and initialize it with a value we get by concatenating the variables 'str002' and 'str003' 

Junior Developer Central JS Practice Exercise - 05

 
Question: 

Write a Javascript program to create a new string adding 'New!' in front of a given string. If the given string begins with 'New!' already then return the original string. 





Answer: 

function newStr (str) {
let str001 = str; 
if (str001.slice(0,4) === 'New!') {
return str001;
} else {
let str002 = 'New! ' + str001; 
console.log(str002); 
}
}




> we declare a function 'newStr'
> it has one parameter 'str' 
> we declare a variable 'str001'
> we initialize it with a value of the argument 'str'
> we then use if / else statements to check if the string 'str001' begins with 'New!' 
> we use the slice function to check if the string 'str001' begins with 'New!' 
> we return the string 'str001' if it does
> if the string 'str001' it does not begin with 'New!' then we declare another variable 'str002' 
> we initialize the value of the same by concatenating 'New! ' (with a space after the exclamation mark) with the original string variable 'str001' 
> we then console.log 'str002'  

Junior Developer Central JS Practice Exercise - 04

 
Question: 

Write a Javascript program to get the current date

Output:

mm-dd-yyyy
mm/dd/yyyy
dd-mm-yyyy
dd/mm/yyyy




Answer: 

function formatDate () {

let date = new Date(); 
let day = date.getDate(); 
let month = date.getMonth() + 1; 
let year = date.getFullYear(); 
let opt1 = `${month}-${day}-${year}`;
let opt2 = `${month}/${day}/${year}`;
let opt3 = `${day}-${month}-${year}`;
let opt4 = `${day}/${month}/${year}`;

console.log(opt1);
console.log(opt2);
console.log(opt3);
console.log(opt4);

};




> we declare a function 'formatDate'
> it has no parameters
> we declare various variables and initialize it with different type of date objects and methods
>> 'date' = new Date ();   ===>>> this will return the date object as it is a constructor
>> 'day' = date.getDate(); ===>>> this method will return the day of the month
>> 'month' = date.getMonth(); ===>>> this method will return the month (0 to 11)
        we shall add 1 as January is 0, February is 1 and so on
>> 'year' = date.getFullYear(); ===>>> this method returns the year
> we then use template literals and save them in different variables as we have multiple outputs
> finally we console log the variables to get our desired output of date in different formats

Junior Developer Central JS Practice Exercise - 03

 
Question: 

Write a Javascript program to replace every character in a given string with the character following it in the alphabet. 





Answer: 

function replaceChar (str) {

str001 = str.toString(); 
str001 = str001.split('').map(char => String.fromCharCode(char.charCodeAt(0) + 1)).join('');
return str001;

}





> this function replaces each character of the string with the next character in the alphabet
> we first declare a function "replaceChar'
> it has one parameter 'str'
> we first convert the 'str' parameter to a string using the 'toString() method
> we save it in the variable 'str001'
> we then use the split method on 'str001' to divide the string in to an array of substrings
> after we have split the string 'str001', we use the map method 
> the map method will create a new array 
> this new array will have the result of calling a function for every array element
>> the function in the map basically has two tasks to complete
>> first task is to convert the array elements to its Unicode value and add 1 to it
>> we use the charCodeAt(0) + 1
>> we add 1 to it, as we have to replace the character with the next character in the alphabet
>> so by doing the first task we shall get an array of Unicode values
>> second task is to convert the array of Unicode values we got, into characters
>> so we use the String.fromCharCode() to convert the Unicode value to characters
> thus we have an array of characters by using the map method
> we then need to create a string from the array of characters as that would be our answer
> so we use the join method after the map method to convert it into a string value
> we then return 'str001' to get our final answer which will be a string that has the characters moved forward
> like this: 'abcde' will become 'bcdef'