3
\$\begingroup\$

I am using a long array of over 300 var & 7,000 lines of code written like this:

var a = [];
var b = [];
var c = [];
var d = [];
var e = [];

a[0] = "a";
b[0] = "b";
c[0] = "c";
d[0] = "d";
e[0] = "e";

a[1] = "1";
b[1] = "2";
c[1] = "3";
d[1] = "4";
e[1] = "5";

a[2] = "one";
b[2] = "two";
c[2] = "three";
d[2] = "four";
e[2] = "five";

Im guessing it is the same as a much cleaner and shorter -

var a = [a,1,one];
var b = [b,2,two];
var c = [c,3,three];
var d = [d,4,four];
var e = [e,5,five];

Is there an easy or automatic way to rewrite the original array like the 2nd method?

\$\endgroup\$

closed as off-topic by Jamal Apr 10 '15 at 5:26

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • \$\begingroup\$ If you have a finite number of elements that you need to add to an array which follow a pattern, use a for loop. If you don't know how many you're going to need, a while loop will do the trick. Loop through them and use the index to assign the numbers accordingly. \$\endgroup\$ – Jonny Sooter Jun 4 '13 at 16:48
4
\$\begingroup\$

First of all I think you meant:

a = ["a","1","one"]; // instead of [a, 1, one]

I handle these rare kind of issues as follow:

  • Open your browser (the following code is tested against Chrome)
  • Open the JavaScript console [Control -Shift -J (Chrome:Windows/Linux)]
  • Copy/paste your own code into the console

and then paste the following code

copy('abcde'.split('').map(function(varName){
return 'var ' + varName + ' = ' + JSON.stringify(window[varName])+';';
}).join('\n'));

If your variable names are more than 1 character use this code instead: (of course the following code won't work with the file example you specified, I changed the variable names for demonstration purpose)

copy(['var1', 'myVar2', 'blablabla'].map(function(varName){
return varName + ' = ' + JSON.stringify(window[varName])+';';
}).join('\n'));
  • Hit enter

the above code will copy the following JavaScript code into your clipboard:

a = ["a","1","one"];
b = ["b","2","two"];
c = ["c","3","three"];
d = ["d","4","four"];
e = ["e","5","five"];

Paste it into your file, save it and that's all!

\$\endgroup\$
  • \$\begingroup\$ wow. Looks good, but it looks like I need to make an array of my vars 1st before I run this. Ill test it out - Thanks \$\endgroup\$ – Jon Jun 5 '13 at 17:35
  • \$\begingroup\$ If your variables follow a specified pattern just tell me what it is and I'll see what I can do about it :) \$\endgroup\$ – FGRibreau Jun 6 '13 at 7:58
  • \$\begingroup\$ They are product codes so dont really have a pattern. I have them in csv format so it should be easy enough. Thanks \$\endgroup\$ – Jon Jun 6 '13 at 11:33
  • \$\begingroup\$ excellent - thanks so much. I went from 180kb file to 80kb, and I think easier to manage file. I dont have var before the variables though. It works but not best practice? \$\endgroup\$ – Jon Jun 6 '13 at 14:59
  • \$\begingroup\$ I added 2 things to the explanation so idiots can follow - the shortkey to the JS console, and hit enter at the end! \$\endgroup\$ – Jon Jun 6 '13 at 15:04
1
\$\begingroup\$

If you have a finite number of elements that you need to add to an array which follow a pattern, use a for loop. If you don't know how many you're going to need, a while loop will do the trick. Loop through them and use the index to assign the numbers accordingly.

for (var i = 0; i < 36; i++) {
    var a = [String.fromCharCode(65 + i).toLowerCase(), i+1, toWords(i) ];
};

console.log(a);    

var th = ['','thousand','million', 'billion','trillion'];
var dg = ['zero','one','two','three','four', 'five','six','seven','eight','nine'];
var tn = ['ten','eleven','twelve','thirteen', 'fourteen','fifteen','sixteen', 'seventeen','eighteen','nineteen'];
var tw = ['twenty','thirty','forty','fifty', 'sixty','seventy','eighty','ninety'];

function toWords(s){
    s = s.toString();
    s = s.replace(/[\, ]/g,'');
    if (s != parseFloat(s))
        return 'not a number';
    var x = s.indexOf('.'); 
    if (x == -1) 
        x = s.length; 
    if (x > 15) 
        return 'too big'; 
    var n = s.split(''); 
    var str = ''; 
    var sk = 0; 
    for (var i=0; i < x; i++) {
        if ((x-i)%3==2) {
            if (n[i] == '1') {
                str += tn[Number(n[i+1])] + ' ';
                i++;
                sk=1;
            } else if (n[i]!=0) {
                str += tw[n[i]-2] + ' ';
                sk=1;
            }
        } else if (n[i]!=0) {
            str += dg[n[i]] +' ';
            if ((x-i)%3==0)
                str += 'hundred ';
            sk=1;
        } 
        if ((x-i)%3==1) {
            if (sk)
                str += th[(x-i-1)/3] + ' ';
            sk=0;
        }
    }
    if (x != s.length) {
        var y = s.length;
        str += 'point ';
        for (var i=x+1; i<y; i++)
            str += dg[n[i]] +' ';
    } 
    return str.replace(/\s+/g,' ');
}
\$\endgroup\$
1
\$\begingroup\$

First of all:

var a = [a,1,one];
var b = [b,2,two];
var c = [c,3,three];
var d = [d,4,four];
var e = [e,5,five];

is not the same as:

var a = ["a",1,one];
var b = ["b",2,two];
var c = ["c",3,three];
var d = ["d",4,four];
var e = ["e",5,five];

Second: Technically, it would have the same effect, to declare an array step by step or in a row.

And no: there is no real way to convert your code automatically from the former to the latter. But perhaps, your question goes in another direction. Perhaps you want a solution to easily build combined arrays. For that task I suggest to take a look at underscore's zip function:

_.zip(['moe', 'larry', 'curly'], [30, 40, 50], [true, false, false]);

outcome:

[["moe", 30, true], ["larry", 40, false], ["curly", 50, false]]

So in your case:

_.zip(["a", "b", "c", ...], ["1", "2", "3", ...], ["one", "two", "three", ...]);

would be, what you are looking for.

\$\endgroup\$
  • \$\begingroup\$ I thought if I had my arrays like the 2nd method my array js file would be a lot smaller, and easier to read etc. The filesize reduction would be my biggest goal - thanks \$\endgroup\$ – Jon Jun 5 '13 at 17:30

Not the answer you're looking for? Browse other questions tagged or ask your own question.