0

I have around 30 values stored as variables:

var a = 1,
    b = 2,
    c = 3,
    ...
    z = 26, 
    aa = 27,
    ab = 28;

that I want to scale. I do so using an array:

array = [a, b, c];
var scale = 5;

for (var i = 0; i < array.length; i++){
    array[i] = array[i] * scale; // Some simple arithmetic
}

To get the new scaled value, I need to reassign my variables.

var a = array[0],
    b = array[1],
    c = array[2],
    ...
    z = array[26], 
    aa = array[27],
    ab = array[28];

This is cumbersome, even if I use destructuring assignment. What is a better way to manage all the information I have?

AlexJ
  • 87
  • 1
  • 10
  • 5
    Numbers and strings are immutable. You can't modify them, you can only reassign. This is why people like data structures like arrays. It's easy to reassign things without having to reference a bunch of individual variable names. – Mark Jul 20 '18 at 22:20
  • @PM77-1 See my edit – AlexJ Jul 20 '18 at 22:23
  • 1
    See [this answer](https://stackoverflow.com/a/3422473/2055998). – PM 77-1 Jul 20 '18 at 22:24
  • @MarkMeyer In my case I am performing a bunch of trigonometry; the values refer to things like angles and lengths of sides of triangles; for that reason I want to use variable names. Would something like a dictionary make more sense? – AlexJ Jul 20 '18 at 22:25
  • 3
    @AlexJ Yes, an object would be a good choice. As mentioned above, you can pass variables through an an array and destructure: `[a, b, c] = [a,b,c].map(i => i*5)`, but that's messier than just using an array or object. – Mark Jul 20 '18 at 22:26
  • Possible duplicate of [Unpacking array into separate variables in JavaScript](https://stackoverflow.com/questions/3422458/unpacking-array-into-separate-variables-in-javascript) – rishat Jul 20 '18 at 22:30

2 Answers2

2

Using plain variables you won‘t find a smarter way. I‘d suggest to use objects instead as arrays are anonymous because you access the content by index instead of a name:

let groupA = { 
     a: 1,
     b: 2,
     c: 3
}

You can then iterate and multiply via

for (let key in groupA) {
    if (groupA.hasOwnProperty(key) {
         groupA[key] *= 5;
    }
}   

but you still can access each field individually

console.log(groupA.a);
1

You have to reassign anyway, but you can do it in a more concise way:

let a = 1,
    b = 2,
    c = 3;

([a, b, c] = [a, b, c].map(v => v * 5));

console.log(b);
ZER0
  • 24,846
  • 5
  • 51
  • 54