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

What is the best way to refine the results from an AJAX request in Datatables?

I have successfully configured a Datatables plugin, set up a new table, and populated it with content using an AJAX call: var table= $("#mytable").DataTable({ ajax: "list.json", columns: [ {"data": "name"}, {"data": "location"}, ...

Leveraging the JavaScript NPM module through import functionality

Currently, I am utilizing the kahoot-api NPM module (GitHub, NPM) that requires JavaScript import. (edit: this is a Node.js package. At the time of writing this, I was unaware of the distinction between JS and Node.js, hence the creation of this question). ...

Displaying properties of objects in javascript

Just starting with JavaScript and struggling to solve this problem. I attempted using map and filter but couldn't quite implement the if condition correctly. How can I find the records in the given array that have a gender of 0 and color is red? let s ...

Error in TypeScript: Module 'stytch' and its corresponding type declarations could not be located. (Error code: ts(2307))

I'm currently developing a Next.js application and encountering an issue while attempting to import the 'stytch' module in TypeScript. The problem arises when TypeScript is unable to locate the module or its type declarations, resulting in t ...

Determine the HTTP status code for a request using Vue.js and Ajax

I need to retrieve the HTTP status code after submitting a form (using the form submission function): return fetch(serviceUrl + 'Collect', { method: "POST", headers: new Headers({ "Content-Type": "application/json", Authoriza ...

Oops! There seems to be an issue with trying to access the 'map' property of undefined within the render method

While working on my project, I encountered an issue with a table from react material ui. The problem arises when attempting to populate the table with data from the state, resulting in an error message stating "cannot read property 'map' of undef ...

How to access JavaScript files from "bower_components" instead of "node_modules" using webpack

With the utilization of main-bower-files in my Gulp compilation tasks, it is not feasible for me to use webpack to require modules from the node_modules directory as it would interfere with the processing of CSS, images, and fonts in my current asset sys ...

Failed to locate lodash during npm installation

I recently set up my project by installing lodash and a few other libraries using npm: npm install grunt-contrib-jshint --save-dev npm install grunt-contrib-testem --save-dev npm install sinon --save-dev npm install -g phantomjs npm install lodash --save ...

Investigating TypeScript Bugs in Visual Studio Code

As I navigate through various sources, I notice that there is a plethora of information available on older versions of VSCode (v1.16.1 - the most recent version at the time of writing) or deprecated attributes in the launch.json file. I have experimented ...

What are the steps to effectively create a cascade of Q promises?

Consider the following scenario as an illustration: I have 3 URLs stored in an array called "urls" The "require" function returns a promise that performs an $http call The code provided is functional, but it doesn't meet my desired outcome since th ...

Toggle class on element based on presence of class on another element

If I have 4 boxes and the user is required to choose one. I aim to assign an active class to the box that the user clicks on. However, if the user selects another box, I want to remove the class from the first clicked box and apply it to the newly clicked ...

NodeJS Express REST API fails to fetch data in GET request

As I work on developing a REST API using NodeJS and Express, I have set up routes for handling "offers". However, when attempting to send a GET request, I receive an empty response along with a 200 status code. Here is the snippet from routes.js: route ...

What is preventing my boolean from being altered?

Creating a basic calculator that can handle single-digit arithmetic. The current code is incomplete and redundant, so please avoid commenting on that. <!doctype html> <html> <head> <title>JavaScript Learning Zone</title> ...

Navigating to a new URL after submitting a form in React

Hello, I am new to React and have created a form that successfully sends data to Firebase. However, after submitting the form, I would like to redirect to /thankyou.html which is outside of the React app. Can someone please guide me on how to achieve this ...

Exploring the World of Micro-Frontends with the Angular Framework

I am conducting research on the best methods for transitioning a large single-page application into a micro-frontend architecture. The concept: The page is made up of multiple components that function independently Each component is overseen by its own ...

Dropdown selection for countries that dynamically updates region choices

Looking to implement some JavaScript, preferably using jQuery, to create a cascading dropdown menu. Initially displaying a list of countries and upon selection, the corresponding regions for that country will be displayed in another dropdown. I assume an ...

Exploring Angular 6 with Universal Karma for effective module testing

Issue I have been facing challenges while testing my Angular 6 application with Karma. I am encountering errors such as: Can't bind to 'ngModel' since it isn't a known property of 'mat-select'. Although the import works in ...

I am looking to retrieve the body's background color using Regular Expressions

Trying to extract the background color from a CSS string: "body{ background-color: #dfdfdf; } " The color could also be in rgba(120,120,120) format. I am looking for a way to extract that color using regular expressions. I have tried using this patt ...

Finding the Client's Private IP Address in React or Node.js: A Comprehensive Guide

Issue I am currently facing the challenge of comparing the user's private IP with the certificate's IP. Is there a method available to retrieve the user's private IP in react or node? Attempted Solution After attempting to find the user&a ...

Is it possible to access the passed arguments in the test description using jest-each?

Utilizing TypeScript and Jest, consider this sample test which can be found at https://jestjs.io/docs/api#testeachtablename-fn-timeout it.each([ { numbers: [1, 2, 3] }, { numbers: [4, 5, 6] } ])('Test case %#: Amount is $numbers.length =&g ...