Recap
Last week I dropped a write up on acing JS interviews and common questions you may encounter. You can find part 1 here.
As usual, if you happen to me up with better, more effective, or even other solutions to these challenges, remember to make a pull request on the github repo.
Challenges continuation...
Once again, the solutions and explanation given in the challenges below, assume that you have a basic understanding of Javascript and especially data types. The challenges below focus on arrays and strings.
Challenge 7 - Longest Word
Return the longest word of a string. Given a sentence write a function that returns the longest word in the sentence. If multiple words, return an array of these words.
function longestWord(sen) {
//? SOLUTION 1 - Return a single longest word
// strip punctuation and create filtered array
const wordArr = sen.toLowerCase().match(/[a-z0-9]+/g);
// sort by length
const sorted = wordArr.sort((a, b) => b.length - a.length);
// return longest word
return sorted[0];
}
function longestWord(sen) {
//? SOLUTION 2 - Return an array and include multiple words if they have the same length
const wordArr = sen.toLowerCase().match(/[a-z0-9]+/g);
const sorted = wordArr.sort((a, b) => b.length - a.length);
const longestWordArr = sorted.filter(
word => word.length === sorted[0].length
);
return longestWordArr;
}
function longestWord(sen) {
//? SOLUTION 3 - Return an array if multiple and single string if only one
const wordArr = sen.toLowerCase().match(/[a-z0-9]+/g);
const sorted = wordArr.sort((a, b) => b.length - a.length);
const longestWordArr = sorted.filter(
word => word.length === sorted[0].length
);
if (longestWordArr.length > 1) {
return longestWordArr;
} else {
return longestWordArr[0];
}
}
Challenge 8 - Chunking arrays
Given an array and a length of n, split the array into chunked arrays of length n.
function chunkArray(arr, len) {
//? SOLUTION 1 - using while loop
const chunkedArr = [];
// set index
let i = 0;
// loop while index is less than array lenngth
while (i < arr.length) {
// slice out from the index to the index + the chink length and push on to the chunked array
chunkedArr.push(arr.slice(i, i + len));
// Increment by chunk length
i += len;
}
// return chunked array
return chunkedArr;
}
the second solution is quite a handful, and it may take a while to understand it
function chunkArray(arr, len) {
//? solution 2
// init an empty array
const chunkd = [];
// Loop through the arr
arr.forEach(val => {
// Get last element
const last = chunkd[chunkd.length - 1];
// Check if last and if last length is equal to the chunk len
if (!last || last.length === len) {
chunkd.push([val]);
} else {
last.push(val);
}
});
return chunkd;
}
Challenge 9 - Flattening arrays
Given an array of arrays, flatten to a single array
function flattenArray(arrays) {
//? Solution 1 - using reduce
return arrays.reduce((a, b) => a.concat(b));
}
solution 2, using apply method. (Fun fact: I actually learnt this recently. I am not sure I still understand it)
function flattenArray(arrays) {
//? Solution 2 - apply method
return [].concat.apply([], arrays);
}
solution 3, using es2015's spread operator
function flattenArray(arrays) {
//? Solution 3 - spread operator
return [].concat(...arrays);
}
Challenge 10 - Anagram
Given two string values, return true if anagram both are anagrams of each other.
According to Wikipedia, an anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. e.g dormitory and dirty room, or elbow and below
This particular solution uses a helper function to compare both strings. We start by making a helper function...
// Helper function
function formatStr(str) {
return (
str
// remove all characters that are not word characters
.replace(/[^\w]/g, '')
// lowercase
.toLowerCase()
// extract each character to form an array
.split('')
// sort all characters
.sort()
// form a string again
.join('')
);
}
then we compare both strings
function isAnagram(str1, str2) {
// using the formatStr helper function, compare both strings
return formatStr(str1) === formatStr(str2);
}
Challenge 11 - Letter changes
Given a string, change every letter of the string to the one that follows it and capitalize the vowels. This solution uses regex to replace character codes and uppercase vowels
function letterChanges(str) {
// using regex
let newStr = str
// lowercase everything
.toLowerCase()
// replace characters
.replace(/[a-z]/gi, char => {
// if character is 'z' or 'Z' return 'a'
if (char === 'z' || char === 'Z') {
return 'a';
} else {
// every character has a character code, so we increse it by 1
return String.fromCharCode(char.charCodeAt() + 1);
}
});
// uppercase the vowels
newStr = newStr.replace(/a|e|i|o|u/gi, vowel => vowel.toUpperCase());
return newStr;
}
Well this is getting quite long, let's continue in part 3. Coming soon.
Until then, have a great time.
Top comments (0)