Developing a column index comparable to that of spreadsheet software

Do you know of a method in Javascript that allows for generating a sequence of strings from A-Z, then moving on to AA-ZZ, and continuing to AAA-AMJ? I'm hoping to avoid nested loops to accomplish this task. I've hit a roadblock and would appreciate any innovative ideas you may have to offer.

Answer №1

Once I had a requirement to create a function in PHP that could convert a numerical column index into its corresponding Excel column name. Fortunately, I found a unique approach in the PHP documentation that utilized modulo of powers of 26. I successfully adapted this function to JavaScript, making it versatile and efficient:

function convertNumToAlpha($num) {
    let $result = '', $index, $num;
    for ($index = 1; $num >= 0 && $index < 10; $index++) {
        $result = String.fromCharCode(65 + ($num % Math.pow(26, $index) / Math.pow(26, $index - 1))) + $result;
        $num -= Math.pow(26, $index);
    }
    return $result;
}

See the original source

Usage examples:

convertNumToAlpha(0); //A
convertNumToAlpha(27); //AB
convertNumToAlpha(1023); //AMJ

Furthermore...

let columns=[];
for(let i=0; i<=1023; i++) {
   columns.push(convertNumToAlpha(i));
}
//["A","B","C",..."AA","AB",..."AMJ"]

For a more concise version:

let columns=[...Array(1024).keys()].map(convertNumToAlpha)

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

A guide on utilizing URL parameters in Express.js to deliver images as static files

Looking to dynamically serve images from an "images" directory in my project based on user input, how can I achieve this? For instance, https://localhost:3000/images?fileName=burger This URL should display the corresponding image in the browser. If any ...

Encountering a glitch while attempting to execute my test on webdriverio

Lately, I've encountered an issue while attempting to execute my webdriverio tests following an upgrade of my node version. The error message that now pops up is: 2022-01-11T12:45:05.628Z DEBUG @wdio/config:utils: Couldn't find ts-node package, n ...

Using AngularJS Scope to Map an Array within a JSON Array

I'm attempting to extract the type and url values from the media2 object within this JSON array and assign them to an AngularJS scope Array. "results":[ { "session2":[ { "__type":"Object", "abou ...

Having trouble getting ng-click to function properly in TypeScript

I've been struggling to execute a function within a click function on my HTML page. I have added all the TypeScript definition files from NuGet, but something seems to be going wrong as my Click Function is not functioning properly. Strangely, there a ...

The React Testing Library encountered an error: TypeError - actImplementation function not found

Encountering a TypeError: actImplementation is not a function error while testing out this component import React from 'react'; import { StyledHeaderContainer, StyledTitle } from './styled'; export const Header = () => { return ( ...

What is the purpose of using a hash in a WebSocket handshake?

When establishing a Websocket connection, the client initiates by connecting to a tcp socket on a server and then performs a handshake. In the client's handshake, there is a base64 encoded key (Sec-WebScoket-Key). The expected response from the serv ...

What is the best way to enable one directive to be utilized across multiple inputs in Angular Material?

Here is a code snippet that I am working with: <md-input-container class="new-paragraph addon-menu"> <label>Post text</label> <textarea ng-model="user.post" rows="3"></textarea> </md-input-container> <md-menu ...

What is the process for modifying a task on my to-do list with a long press?

I'm currently working on implementing a task update feature in my project. However, I've encountered an issue where the prompt only works in the browser environment. Is there a way to make this work in React Native or are there any alternative so ...

The code inside the promise .then block is executing long before the promise has completed its

After spending quite some time working on this messy code, I finally have a functioning solution: loadAvailabilities() { let promises = []; let promises2 = []; let indexi = 0; //return new Promise((resolve, reject) => { this.appo ...

Connect the CSS active state to a JavaScript event

.el:active{ background:red; } Is there a way to associate the above CSS active state with a JavaScript event, like this: $('.el').on('active', function(){ img.show(); }); I want the image to remain visible when el is presse ...

Database not receiving input data from AngularJS form submission

Having some trouble saving form data to the database using angularjs. Not sure what I'm doing wrong. Here's my HTML form: <form id="challenge_form" class="row" > <input type="text" placeholder="Challenge Name" ng-model="ch ...

Using Jquery to Connect a Change Event to Child Elements

<form id="duration"> <label for="change-chart-type-24H" > ; <input style="display:none;" name="chart-type" id="change-chart-type-24H" type="radio" value="24H">24H ...

Adding values to an array with the click of a submit button in React JS

I have a unique challenge with creating a form that includes custom inputs. const Input = (props) => { return ( <div> <label className={classes.label}>{props.label} <input className={classes.input} {... ...

When working with AngularJS, you can enhance your application by implementing a global AJAX error handler if one has

Is there a way to set a global AJAX handler that will only be called if an error handler is not already defined for a specific AJAX call? Some of my AJAX calls need to execute certain logic if an error occurs (such as re-enabling a button), while others s ...

React 18 doesn't trigger component re-rendering with redux

In my code, I have implemented a custom hook to handle global data fetching based on user authentication. Here is an example of the hook: const userState = useSelector(state => state.user.state) useEffect(() => { if(userState === "authentic ...

Display and conceal frequently asked questions using JQuery

I'm currently facing an issue with using JQuery to toggle between showing and hiding content when a user clicks on a specific class element. Here is my HTML code: <div class="faqSectionFirst"> Question? <p class="faqTextFirst" style=' ...

Include the JS file after finishing the control processing

I've been grappling with an issue for several days now. The view I have is populated by my controller through an API call, which works perfectly fine in rendering the HTML. $http.get(url). success(function(data, status, headers, config) { ...

Assign the output of a function to a variable

I am trying to retrieve data from a function call in nodejs and assign it to a variable. The desired output should be "Calling From Glasgow to Euston", but I'm currently getting "Calling From undefined to undefined". Here is the code snippet: functi ...

The Vuetify rating system seems to be having trouble displaying

I've integrated the Vuetify rating component into my app (https://vuetifyjs.com/en/components/ratings#ratings), but I'm facing an issue. Despite having Vuetify 1.5.5 installed and working with other components like buttons, the stars in the ratin ...

What is the method to define a loosely typed object literal in a TypeScript declaration?

We are currently in the process of creating TypeScript definitions for a library called args-js, which is designed to parse query strings and provide the results in an object literal format. For example: ?name=miriam&age=26 This input will produce th ...