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?



American National Standards Institute Inc.

comments powered by Disqus

Related Posts

The Great JavaScript Debate: To Semicolon or Not?

Since I’ve started learning this language, JavaScript has undergone some heavy changes. Most notably, it seems to be the norm to not use semicolons anymore.

Read more

Hacktoberfest 2024: Get a Free JavaScript Today Sticker

October is here, and that means one thing in the tech world—Hacktoberfest! This annual event, powered by DigitalOcean, Cloudflare, Quira, and other sponsors, encourages developers of all skill levels to contribute to open-source projects.

Read more

Creating a Real Time Chat Application with React, Node, and TailwindCSS

In this tutorial, we will show you how to build a real-time chat application using React and Vite,as well as a simple Node backend.

Read more