What is the best way to determine the final letter of a column in a Google Sheet, starting from the first letter and using a set of

My current approach involves generating a single letter, but my code breaks if there is a large amount of data and it exceeds column Z.

Here is the working code that will produce a, d:

const countData = [1, 2, 3, 4].length;
const initialLetter = 'A'.toLowerCase();
const initialLetterNumber = initialLetter.charCodeAt(0) - 97;
const lastLetter = String.fromCharCode(
  initialLetterNumber + countData - 1 + 97
);

console.log(initialLetter, lastLetter);

In contrast, here is the non-working code for which I aim to get z, ac.

const countData = [1, 2, 3, 4].length;
const initialLetter = 'Z'.toLowerCase();
const initialLetterNumber = initialLetter.charCodeAt(0) - 97;
const lastLetter = String.fromCharCode(
  initialLetterNumber + countData - 1 + 97
);

console.log(initialLetter, lastLetter);

Below are some example inputs and their corresponding expected outputs:

input: a, data length: 1 output: a,
input: a, data length: 2 output: b,
input: a, data length: 3 output: c,
input: a, data length: 4 output: d,
input: a, data length: 5 output: e,

input: z, data length: 1 output: z,
input: z, data length: 2 output: aa,
input: z, data length: 3 output: ab,
input: z, data length: 4 output: ac,
input: z, data length: 5 output: ad,

input: ad, data length: 1 output: ad,
input: ad, data length: 2 output: ae,
input: ad, data length: 3 output: af,
input: ad, data length: 4 output: ag,
input: ad, data length: 5 output: ah,

input: az, data length: 1 output: az,
input: az, data length: 2 output: ba,
input: az, data length: 3 output: bb,
input: az, data length: 4 output: bc,
input: az, data length: 5 output: bd,

input: bz, data length: 1 output: bz,
input: bz, data length: 2 output: ca,
input: bz, data length: 3 output: cb,
input: bz, data length: 4 output: cc,
input: bz, data length: 5 output: cd,

...

Answer №1

There are two functions that can be used to convert between an integer value and a string, allowing for flexibility in manipulating numerical data and encoding it into a string format.

One function decodes a string into an integer by iterating over the characters and performing calculations based on their character codes. The other function encodes an integer into a string, breaking down the number into parts and converting them into specific characters.

const
    decode = string => [...string].reduce((r, c) => r * 26 + parseInt(c, 36) - 9, 0) - 1,
    encode = integer => {
        let result = '';
        do {
            result = (integer % 26 + 10).toString(36) + result;
            integer = Math.floor(integer / 26) - 1;
        } while (integer >= 0)
        return result;
    };

for (let i = 0; i < 26 * 27 + 1; i++) {
    const s = encode(i);
    document.getElementById('out').innerHTML += [i, s, decode(s)].join(' ') + '\n';
}
<pre id="out"></pre>

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

Restrict a class to contain only functions that have a defined signature

Within my application, I have various classes dedicated to generating XML strings. Each of these classes contains specific methods that take input arguments and produce a string output. In order to enforce this structure and prevent the addition of methods ...

Ways to retrieve information beyond the scope of the 'then' method

One issue I am facing involves a piece of code that is only accessible inside of the 'then' function. I need to access it outside of this block in order to utilize it in other parts of my program. $scope.model = {'first_name':'&ap ...

Adding an overlay to a material UI table row: Step by step guide

My code is rendering a row in the following format: `<TableRow key={row.name} > <TableCell>{row.empId}</TableCell> <TableCell>{row.userId}</TableCell> <TableCell>{row.name}</TableCell> <TableCell>{r ...

Integrating Mailchimp with MongoDB and Node.js

As of now, I am managing a database of users in MongoDB and my goal is to provide them with regular updates on new content available on a real-estate marketplace website on a daily basis. My plan is to send out email notifications to each user every day w ...

I want to add an LI element to a UL by utilizing jQuery in forms.js

I have several forms on my webpage and I am utilizing jQuery form.js to save each comment that users post. After saving the comment successfully, I want to append it to the UL tag. Although the saving part is functioning properly, I am encountering difficu ...

What is the correct way to implement Axios interceptor in TypeScript?

I have implemented an axios interceptor: instance.interceptors.response.use(async (response) => { return response.data; }, (err) => { return Promise.reject(err); }); This interceptor retrieves the data property from the response. The re ...

Adjust the height of a div using jQuery once the AJAX call retrieves the data

There is a div that always matches the height of the adjacent div, depending on the content loaded in it. This setup was functioning properly until I implemented a search feature using jQuery. Now, when I perform a search, the element used in the jQuery ca ...

Leveraging environment variables in NextJS - passing values to the client side

I'm facing a frustrating issue with my project in server mode. We need to pass environment variables at runtime and access them on both the server and client side. Following the publicRuntimeConfig method from the documentation, everything works fine ...

Burst or displace meshes outward from the center

I am attempting to separate all the meshes that make up the loaded obj file from each other in order for the user to easily view each mesh individually. I am striving to replicate a similar functionality as shown in this example: Demo To achieve this ef ...

Transforming JQuery text upon selecting preloaded content with fire

When I copy the first name into the last name field, everything works fine for new names on the page. However, once a few names have been entered and the browser starts showing a history of names, the function doesn't work anymore if a pre-filled or o ...

When the modal is closed, the textarea data remains intact, while the model is cleared

My challenge involves a simple modal that includes a text area. The issue I am facing is resetting the data of the textarea. Below is the modal code: <div class="modal fade" ng-controller="MyCtrl"> <div class="modal-dialog"> <d ...

The HTML table is not fully filled with data from the XML file

Trying to populate an HTML table using XML data retrieved from an AJAX call is proving to be a challenge for me. The main issue I am facing is the inability to fully populate the HTML table. Being new to AJAX, understanding how XML interpretation works an ...

Where can I locate the list of events supported by CKEditor 4?

Looking for the list of available events I attempted to locate the event list in the official documentation, but unfortunately came up short. I resorted to searching through the source code using .fire("/s+") to identify all available events. However, thi ...

A guide on arranging map entries based on their values

The map displayed below, as represented in the code section, needs to be sorted in ascending order based on its values. I would like to achieve an end result where the map is sorted as depicted in the last section. If you have any suggestions or methods o ...

Enhancing the efficiency of Angular applications

My angular application is currently coded in a single app.module.ts file, containing all the components. However, I am facing issues with slow loading times. Is there a way to improve the load time of the application while keeping all the components within ...

Exploring the dynamic data loading feature in Vue 3 by fetching data from the server and displaying it using a v-for

I am encountering an issue where I want to display data dynamically from a database using a v-for loop. However, when I attempt to push new data into the array, they show correctly in a console.log() but do not reflect any changes in the template. I have ...

Cutting off the final character in CKEditor for AngularJS

I have come across an issue with my web page that utilizes CKEditor for creating message edit panes. The problem arises when I try to send a message and the content retrieved from CKEditor is missing the last letter. Below is a snippet of what I believe t ...

Establish a single route for executing two different statements in MSSQL: one for updating and the other for inserting data into the MS-SQL

I have a Node application where I currently insert data into one table, but now I also need to insert it into another table. The issue is that I am unsure how to execute a second promise for this task. var query = "first SQL query..."; var query2 = "new ...

Saving many-to-many relationships with entities that are already saved in TypeORM

As a beginner in Typeorm, I have been working on a web page with Angular + Typeorm for the past few weeks. Despite my efforts to resolve this issue by myself and researching previously asked questions here on Stackoverflow, I have unfortunately been unable ...

Error encountered in TypeScript's Map class

When working with TypeScript, I keep encountering an error message that reads "cannot find name Map." var myMap = new Map(); var keyString = "a string", keyObj = {}, keyFunc = function () {}; // assigning values to keys myMap.set(keyString, "val ...