Number to Ordinal Suffix

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will explore a JavaScript function that takes a number and returns it as a string with the correct ordinal indicator suffix. The function will use the modulo operator to find values of single and tens digits, and then determine which ordinal pattern digits match. We will also handle the special case of teens pattern digits and use the appropriate ordinal for these numbers.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/BasicConceptsGroup -.-> javascript/array_methods("`Array Methods`") subgraph Lab Skills javascript/variables -.-> lab-28654{{"`Number to Ordinal Suffix`"}} javascript/data_types -.-> lab-28654{{"`Number to Ordinal Suffix`"}} javascript/arith_ops -.-> lab-28654{{"`Number to Ordinal Suffix`"}} javascript/comp_ops -.-> lab-28654{{"`Number to Ordinal Suffix`"}} javascript/array_methods -.-> lab-28654{{"`Number to Ordinal Suffix`"}} end

Function to Convert Numbers to Ordinal Suffix

To convert a number to an ordinal suffix, use the toOrdinalSuffix function.

  • Open the Terminal/SSH and type node to start practicing coding.
  • The function takes a number as input and returns it as a string with the correct ordinal indicator suffix.
  • Use the modulo operator (%) to find the values of the single and tens digits.
  • Find which ordinal pattern digits match.
  • If the digit is found in the teens pattern, use the teens ordinal.
const toOrdinalSuffix = (num) => {
  const int = parseInt(num),
    digits = [int % 10, int % 100],
    ordinals = ["st", "nd", "rd", "th"],
    oPattern = [1, 2, 3, 4],
    tPattern = [11, 12, 13, 14, 15, 16, 17, 18, 19];
  return oPattern.includes(digits[0]) && !tPattern.includes(digits[1])
    ? int + ordinals[digits[0] - 1]
    : int + ordinals[3];
};

Here is an example of using the toOrdinalSuffix function:

toOrdinalSuffix("123"); // '123rd'

Summary

Congratulations! You have completed the Number to Ordinal Suffix lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like