Add the appropriate ordinal suffixes ('-st', '-nd', '-rd', '-th') to each item based on its index

Imagine having an array filled with various option values, such as:

var options = ["apple", "banana", "cherry", "date", "elderberry", "fig", "grapefruit", "honeydew", "kiwi", "lemon", "mango", "nectarine", "orange", "pear", "quince", "raspberry", "strawberry", "tangerine", "ugli fruit", "vanilla bean", "watermelon", "ximenia", "yellow plum", "zucchini"];

If there was a need to convert these into formatted strings that include their position in the array, like this:

var result = ['1st option is "apple"', '2nd option is "banana", '3rd option is "cherry"', '4th option is "date"',...];

An attempt has been made to achieve most of it using the following code:

var result = [];
for(var i = 0; i < options.length; i++){
    result.push((i+1)+' option is "'+options[i]+'"');
}

This code generates strings similar to 1 option is "apple". However, adding the correct suffixes ('st', 'nd', 'rd', 'th') based on the position remains a challenge. Assistance in resolving this issue would be greatly appreciated. Thank you!

Answer №1

One way to handle suffixes is by storing them in an array and matching them with the corresponding index:

const arr = [...'abcdefghijklmnopqrstuvwxyz'];
const suffixes = ['th', 'st', 'nd', 'rd'];

const result = arr.map((item, i) => 
  (idx = ~~(i % 10) + 1 > 3 || ~~(i / 10) == 1 ? 0 : ~~(i % 10) + 1, 
  `${i+1}-${suffixes[idx]} options is '${item}'`));

console.log(result);
.as-console-wrapper {min-width: 100%}

Answer №2

Give this Code a try – it's effective:

https://en.wikipedia.org/wiki/Ordinal_indicator#English

-st is utilized for numbers that end in 1 (e.g. 1st, pronounced first)

-nd is utilized for numbers that end in 2 (e.g. 92nd, pronounced ninety-second)

-rd is utilized for numbers that end in 3 (e.g. 33rd, pronounced thirty-third)

An exception to the above rules is seen with all "teen" numbers ending in 11, 12, or 13 which use -th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth)

-th is used for all other numbers (e.g. 9th, pronounced ninth).

var arr = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"];

function addSuffix(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "-st";
    }
    if (j == 2 && k != 12) {
        return i + "-nd";
    }
    if (j == 3 && k != 13) {
        return i + "-rd";
    }
    return i + "-th";
}

var result = [];
for (var i = 0; i < arr.length; i++) {
    result.push(`${addSuffix(i + 1)} option is  '${arr[i]}'`);
}
console.log(result);

Answer №3

If you need a function to determine the suffix for numbers, you can utilize the modulo operator %. Here is an example of how such a function could be implemented:

function findSuffix(num) {
    let remainder = num % 10;

    if(remainder === 1 && num != 11) { return 'st'; }
    else if(remainder === 2 && num != 12) { return 'nd'; }
    else if(remainder === 3 && num != 13) { return 'rd'; }
    else { return 'th'; }
}

You can use this function in combination with a loop to add the appropriate suffix to each number in an array:

var finalResult = [];
for(var n = 0; n < array.length; n++){
    finalResult.push((n+1) + "-" + findSuffix(n+1) + " option is "'+array[n]+'"');
}

Answer №4

Give this a shot:

const  array= ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape", "honeydew", "iceberg lettuce", "jackfruit", "kiwi", "lemon", "mango", "nectarine", "orange", "pear", "quince", "raspberry", "strawberry", "tangerine", "ugli fruit", "vanilla bean", "watermelon", "ximenia caffra", "yellow passion fruit", "zucchini"];

const suffix = (num) => (["st","nd","rd"][((num+90)%100-10)%10-1] || "th")

const output  = array.map((val,i)=> `${i+1}-${suffix(i+1)} choice is '${val}'`);

console.log(output);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Create an interactive webpage that automatically generates new HTML elements after retrieving JSON data from a Web API during page load

I am currently in the process of developing a hybrid Android App using Phonegap/Apache Cordova. The main function of my app is to retrieve data from my web API, which is being served through JSON. I have implemented the following code snippet for this task ...

The component <FormControl /> does not support the variant prop

It's perplexing to me why <FormControl /> doesn't seem to accept the prop variant. Even though the documentation suggests that this prop is available. import React from "react"; import { render } from "react-dom"; import FormControl from " ...

Is there a way to preserve the original color format without converting it to RGB

When applying a hsl color in JavaScript, it ends up being converted to RGB instead of staying as an HSL color. document.body.style.backgroundColor = "hsl(0,100%,50%)" document.body.style.backgroundColor; // "rgb(255, 0, 0)" I wanted to set an HSL color a ...

Update the Vue method

Is there a way to optimize the following method or provide any suggestions on what can be improved? I am trying to create a function that converts author names from uppercase to only the first letter capitalized, while excluding certain words ('de&apo ...

Activate the element by simulating a button click on another element

I created a "copy-button" component that is utilized in various parts of the application, allowing users to copy information to their clipboard. This component has two bindings: buttonText and buttonClass, which can be used to customize the text displaye ...

Use JavaScript and AJAX to easily assign multiple variables with unique IDs to an array with just one click

This function is no longer supported Original query : I would greatly appreciate any assistance and guidance. I am attempting to create a function that moves selected products from the Cart to another table so I can reorder them according to customer de ...

Creating an embedded link to a website that adjusts to different screen sizes while also dynamically changing

I've been developing a personalized site builder that includes an iframe for previewing responsive websites. In order to make the site 'zoomed out' and not appear in mobile size, I'm utilizing CSS scale and transform origin as shown bel ...

NextJS: Retrieve the information in its initial state

Is there a way to retrieve the original format of a value? For example: The values in my textarea are: Name: Your Name Email: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f980968c8b9c94989095b994989095d79a9694">[email ...

How to eliminate ampersands from a string using jQuery or JavaScript

I'm having trouble with a seemingly simple task that I can't seem to find any help for online. My CSS class names include ampersands in them (due to the system I'm using), and I need to remove these using jQuery. For example, I want to chan ...

Using Django's JSONField Nested within an ArrayField

I am encountering an issue when trying to insert data into a field using ArrayField with JSONField nested inside. models.py locations = ArrayField(JSONField(null=True, blank=True), blank=True, null=True) Insert location_arr = [{"locations": "loc1", "amou ...

transform regex into an array enclosed in parentheses

Hello there, I seem to be facing an issue in finding a suitable solution for my problem. Within my string, I have the following text: anim(10, <-0.016, -0.006, 0.217>, <0.000, 0.000, 0.707, 0.707>, <0.016, 0.010, 0.012>); I am aiming t ...

Using the html5-canvas element to drag connected lines

Here is an example of creating four points and connecting them: sample. My goal is to make it possible to drag the entire line connection when clicking on it, but when clicking on a circle, only that specific circle should be extended (already implemented ...

Error encountered when using the enter or return key with directive syntax

Newbie Alert I'm encountering something strange while attempting to create a custom directive in AngularJS. When I input this code: myModule.directive('myTab', function(){ console.log('--Inside TAB directive--'); return ...

A guide on effectively utilizing ref forwarding in compound component typing

I am currently working on customizing the tab components in Chakra-ui. As per their documentation, it needs to be enclosed within React.forwardRef because they utilize cloneElement to internally pass state. However, TypeScript is throwing an error: [tsserv ...

Choosing an embedded iframe using selenium in javascript with node-js

When working with the selenium webdriver module in node-js, I encountered an issue trying to select a nested iframe within another iframe. Here's an example scenario: <iframe id="firstframe"> <div id="firstdiv"></div> <ifr ...

What is the reason behind JavaScript events causing a page refresh?

My code uses RegExp to search through an array of strings based on user input: Clinica.prototype.pesquisarDoente = function () { var exp = document.getElementById("pesquisaInput").value; var lista = document.getElementById("listaDoentes"); if ...

Tips for resolving the error "Parsing near 'Unexpected end of JSON input while parsing...' for...'mocha':'^3.2.0','s'":

Once I've successfully set up react and react-dom, the next step is to install webpack. However, I encountered an error during this process. To troubleshoot, I decided to install babel-loader first to ensure that both npm and my internet connection a ...

Issue: The hydration process has failed due to a discrepancy between the initial UI and the server-rendered content when utilizing the Link element

Exploring Next.js, I stumbled upon the <Link/> component for page navigation. However, as I utilize the react-bootstrap library for my navbar, it offers a similar functionality with Nav.Link. Should I stick to using just Link or switch to Nav.Link? ...

Silhouettes dancing across handcrafted designs

I have been trying to create a custom geometry using vertices and faces, but I am facing an issue where the geometry does not cast shadows on itself and the faces all have the same color as it rotates. I have attempted various solutions but haven't ha ...

Manipulate the DOM to remove a checkbox using JavaScript

I'm brand new to exploring the world of Javascript and could use some guidance with this task. I have a collection of checkboxes that I'd like to manipulate so that when one is checked, it disappears from the list automatically. I've come ac ...