chris
chris

Reputation: 36957

Creating Column index similar to spreadsheets

Is there a way in Javascript, that I can come up with a series of strings that go A-Z, and when reaching Z, starts over with AA-ZZ, then on to AAA-AMJ? Cause I am trying to think of anything that wouldn't have me looping over loops over loops to do it. And I am stuck and open for ideas at this point.

Upvotes: 3

Views: 65

Answers (1)

chiliNUT
chiliNUT

Reputation: 19592

I had to do this once in php; that is, I needed a function that would take a numerical column index as input and spit out the excel column name. There is a clever function in the php documentation that does it by using modulo of powers of 26. It can be easily converted to js:

function num2alpha($n) {
    let $r = '',$i , $n;
    for ($i = 1; $n >= 0 && $i < 10; $i++) {
        $r = String.fromCharCode(65 + ($n % Math.pow(26, $i) / Math.pow(26, $i - 1))) + $r;
        $n -= Math.pow(26, $i);
    }
    return $r;
}

Original Source

Usage:

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

so...

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

or more tersely

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

Upvotes: 2

Related Questions