Three Simple Algorithms with JavaScript
You might have seen some of these algorithm challenges before, but that’s okay, we’re offering a few solutions to each of them, to help give you a better understanding of them and enhance your problem-solving abilities for other algorithms you might come across in the future.
Reverse a String
Reversing a string is perhaps one of the first algorithmic challenges you will see. It is pretty easy to solve it, especially in JavaScript.
Directions
Given a string, return a new string with the reversed order of characters
Examples
reverse('apple') === 'leppa'
reverse('hello') === 'olleh'
reverse('Greetings!') === '!sgniteerG'
Solution(s):
The quick and easy way:
function reverse(str) {
return str.split("").reverse().join("");
}
console.log(reverse("apple"));
// Outut: 'leppa';
Using .reduce()
:
function reverse(str) {
return str.split("").reduce((rev, char) => char + rev, "");
}
console.log(reverse("apple"));
// Outut: 'leppa';
Using a for of
loop:
function reverse(str) {
let reversed = "";
for (let character of str) {
reversed = character + reversed;
}
return reversed;
}
console.log(reverse("apple"));
// Outut: 'leppa';
Reverse an Int
Reversing an int is much like reversing a string, only that there’s a small change you must keep in mind - changing the data type of the returned value to be a Number.
Directions
Given an integer, return an integer that is the reverse ordering of numbers.
Examples
reverseInt(15) === 51
reverseInt(981) === 189
reverseInt(500) === 5
reverseInt(-15) === -51
reverseInt(-90) === -9
Solution(s):
Using parseInt()
:
function reverseInt(n) {
const reversed = n.toString().split("").reverse().join("");
return parseInt(reversed) * Math.sign(n);
}
console.log(reverseInt(15));
// Output: 51
We only offer one solution for this because it’s so similar to the previous challenge.
Capitalize a String
Now that we’ve got two reversals out of the way, we’ll explore another fun challenge – Capitalizing a string.
Directions
Write a function that accepts a string. The function should capitalize the first letter of each word in the string then return the capitalized string.
Examples
capitalize('hello, there!') --> 'Hello, There!'
capitalize('a lazy fox') --> 'A Lazy Fox'
capitalize('look, it is working!') --> 'Look, It Is Working!'
Solution(s):
With a for
loop:
function capitalize(str) {
let result = str[0].toUpperCase();
for (let i = 1; i < str.length; i++) {
if (str[i - 1] === " ") {
result += str[i].toUpperCase();
} else {
result += str[i];
}
}
return result;
}
console.log(capitalize("hello, there!"));
// Output: 'Hello, There!'
With a for of
loop:
function capitalize(str) {
const words = [];
for (let word of str.split(" ")) {
words.push(word[0].toUpperCase() + word.slice(1));
}
return words.join(" ");
}
console.log(capitalize("hello, there!"));
// Output: 'Hello, There!'
That’s it!
There we have it, three simple algorithms solved with JavaScript. Stick around, there will be many more articles like this. Let us know what you think in the Disqus comments below. Would you like us to write about a particular algorithm or data structure?
Related Posts
The Best Way to Learn How to Code in 2024
Codecademy has been around for awhile now, but we felt this masterful site deserved to be highlighted in an article. It is one of the resources I originally used when I was learning how to code.
Read moreUnveiling the Fascination of the Collatz Conjecture: Exploring Sequence Creation with JavaScript
The Collatz Conjecture, also known as the 3x+1 problem, is a fascinating mathematical puzzle that has intrigued mathematicians for decades. It has sparked publications with titles such as The Simplest Math Problem Could Be Unsolvable, or The Simple Math Problem We Still Can’t Solve because it is, indeed, rather simple-looking.
Read moreThe Art of Data Visualization: Exploring D3.js
Data is everywhere, flowing into our applications from various sources at an unprecedented rate. However, raw data alone holds little value unless it can be transformed into meaningful insights.
Read more