Three Simple Algorithms with JavaScript
Javascript Algorithms

Three Simple Algorithms with JavaScript

4 min read

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?



American National Standards Institute Inc.

About the Author

Matt Fay

Matt Fay

Matt is the founder of JavaScript Today, a platform dedicated to high-quality JavaScript education and commentary. With a deep curiosity for technology, he gravitates toward understanding how things work and has been diving into the world of information security. Outside of coding, Matt enjoys exploring languages; he can understand some Russian and Italian, and is currently learning Thai.

Learn AI Skills with Codecademy (729x90)

Discussion (Loading...)

Join the conversation

Join the Discussion

Sign in to share your thoughts and engage with the JavaScript Today community.

Loading comments...

Related Articles

Continue your learning journey with these related posts

Never Miss a JavaScript Update

Join our community of developers and receive insightful articles and coding tips every week.