Basic JavaScript Algorithms
Dan Norris / 20th Mar 2020
1 min read
I’ve been working through a lot of basic JavaScript algorithms - some of which were useful problems to keep a note of for future reference.
I need to come back to this as it’s helped to identify weaknesses I have around my ability to refactor using different approaches, e.g. recursion, reduce, map, etc.
Reverse a string
1function reverseString(str) {2 let newArr = str.split("");3 console.log(newArr);4 let revArr = [];56 for (let i = newArr.length - 1; i >= 0; i--) {7 revArr.push(newArr[i]);8 console.log(revArr);9 }10return revArr.join("");11}1213reverseString("hello");
Factorialise a number
Using recusion here. This can be rewritten a number of different ways, e.g. tail recursion, for statement and reduce()
.
Explanation on recursion here.
1function factorialize(num) {2 if (num === 0) {3 return 1;4 }5 return num * factorialize(num - 1);6}78factorialize(5);
Same problem using tail recusion. I think my brain exceeded its maximum call stack size trying to understand this.
1function factorialize(num, factorial = 1) {2 if (num == 0) {3 return factorial;4 } else {5 return factorialize(num - 1, factorial * num);6 }7}89factorialize(5);
Check typeof()
value
1function booWho(bool) {2 if (typeof(bool) === "boolean") {3 return true;4 } else {5 return false;6 }7}8booWho(null);
Converting string to sentence case
Again, rewritten a number of different ways. Originally tried a regex pattern with replace()
but couldn’t figure out how to get the callback function to return the right value.
This solution uses map()
, split()
and replace()
.
1function titleCase(str) {2 let newArray = str.toLowerCase().split(" ");3 // console.log(newArray);45 let result = newArray.map(function(val) {6 // console.log(val.replace(val.charAt(0), val.charAt(0).toUpperCase()));7 return val.replace(val.charAt(0), val.charAt(0).toUpperCase());8 })9 return result.join(" ");10}11titleCase("I'm a little tea pot");1213// returns "I'm A Little Tea Pot
Edit: found a solution using a regex pattern, which looks a lot easier.
1function titleCase(str) {2 return str.toLowerCase().replace(/(^|\s)\S/g, L => L.toUpperCase());3}
Copying array into other array (in order)
Using splice
here and the spread ...
operator. Looks like you could iterate here and use slice
to copy the array but using ...
was just faster and cleaner.
The n
argument indicates the indice you want to start inputting arr1
into arr2
.
1function frankenSplice(arr1, arr2, n) {23 /*4 console.log(arr2);5 console.log(arr1)6 console.log(n);7 */89 let result = [...arr2];10 // console.log(result);1112 result.splice(n, 0, ...arr1);13 /*14 console.log(arr2);15 console.log(arr1);16 */1718 return result;19}20frankenSplice([1, 2, 3], [4, 5, 6], 1);21// result returns [4, 1, 2, 3, 5, 6]
Removing falsy values from an array
Pretty straightforward exercise which removes false bool values from an array, then uses filter()
to remove them.
You could probably use a switch
statement here with fall through instead of the if
statement and map()
instead of filter()
to potentially remove the values (?).
1function bouncer(arr) {2 for (let i = 0; i < arr.length; i++) {3 if (arr[i] === false |4 arr[i] === null |5 arr[i] === 0 |6 arr[i] === "" |7 arr[i] === undefined |8 arr[i] === NaN) {9 arr.splice(i, 2, false);10 }11 }1213let result = arr.filter(falsy => {14 return falsy != false;15})1617return result;18}1920bouncer([7, "ate", "", false, 9]);2122// result returns [7, "ate", 9]
Sorting array of numbers ascending (and finding indice)
Tried solving this with a loop but then later realised there is a method for this called sort()
. You can then later find the index using either findIndex()
or indexOf()
.
1function getIndexToIns(arr, num) {2 arr.push(num);3 arr.sort(function(a, b) {4 return a - b;5 });67 // console.log(arr);8 // console.log(num);9 return arr.indexOf(num);10}1112getIndexToIns([40, 60], 50);
Check that all letters in array match other array
Using split()
, every()
and toLowerCase()
here to firstly split the second element into characters, lowercase to make it easier to evaluate and then using every()
to compare against the letters in the first element.
1function mutation(arr) {2 return arr[1]3 .toLowerCase()4 .split("")5 .every(function(letter) {6 return arr[0].toLowerCase().indexOf(letter) != -1;7 });8}910mutation(["hello", "hey"]);11// returns false
Split array into n groups
This splits the original array into a multi-dimensional array split into n
number of groups.
Don’t forget the second parameter for slice()
is an index compared to splice()
which is the number of elements removed. slice()
will also just extract to the end of the sequence if second para. is greater than length array.
1function chunkArrayInGroups(arr, size) {23 let newArray = [];4 for (let i = 0; i < arr.length; i += size) {5 newArray.push(arr.slice(i, i + size));6 }7 return newArray;8}910chunkArrayInGroups(["a", "b", "c", "d"], 2);11// returns [["a", "b"], ["c", "d"]]