-1

I have four variables and I want to change their values using a function where I just can put in an array storing the variables. I'm making a game which uses a coordinate system and therefore I have four coordinates that I want to constantly update with y-axis and x-axis. I have one array, yAxis, with all y values and one array, xAxis, with all x values. I want to combine them into the coordinates. Of course, I can update them using the following code:

yAxis = [10, 10, 9, 9];
xAxis = [4, 4, 5, 5];

coordinate1 = "" + yAxis[0] + xAxis[0];
coordinate2 = "" + yAxis[1] + xAxis[1];
coordinate3 = "" + yAxis[2] + xAxis[2];
coordinate4 = "" + yAxis[3] + xAxis[3];

But instead of changing their values like earlier I would like to do something like this: This function will take the array below, coordinatesArray as a, yAxis as b, and xAxis as c. Then x is just an integer.

test(a, b, c){
  for(x = 0; x < 4; x++){
    a[x] = "" + b[x] + c[x];
  }
}

and then I would call this function like this:

coordinatesArray = [coordinate1, coordinate2, coordinate3, coordinate4];
test(coordinatesArray, yAxis, xAxis);

What it then should do with whatever array I run the test function with:

coordinatesArray[0] = "" + yAxis[0] + xAxis[0];
coordinatesArray[1] = "" + yAxis[1] + xAxis[1];
coordinatesArray[2] = "" + yAxis[2] + xAxis[2];
coordinatesArray[3] = "" + yAxis[3] + xAxis[3];

And for example coordinatesArray[0] should then represent coordinate1.

So I would create an array to store the variables so I can easily change which variable to target. The problem though, when I run this, a[x] isn't the variable name, instead, it is their values which means this doesn't work. So my question is, is there any way to store the variables' names in an array so I can target them using a function similar to the one I showed? I want to store the names of the variables in an array and then be able to use the name to target the variable so I can change their values.

EmilSun03
  • 3
  • 5
  • what is `test` doing? – Nina Scholz Mar 25 '20 at 18:05
  • why do you assign values to `coordinatesArray` first and then do the same in `test`? please add a working example and the wanted result. – Nina Scholz Mar 25 '20 at 18:12
  • I've tried to explain better. Sorry if I'm not that good at explaining, I've just started programming. Thx for any help :) – EmilSun03 Mar 25 '20 at 18:20
  • i have a problem with `coordinatesArray`. first you assign values `coordinatesArray = [coordinate1, coordinate2, coordinate3, coordinate4];` and then you call `test`, where you assign the same values. why twice? – Nina Scholz Mar 25 '20 at 18:23
  • the thing is that I want an array, here coordinatesArray, to store the names of the variables. then I want my function to update the values that the variables have – EmilSun03 Mar 25 '20 at 18:25
  • is there some way that I can store all the variables' names and then target them and change their value? – EmilSun03 Mar 25 '20 at 18:27
  • i understand. you finally want the values in `coordinate1` and so on. that is not really possible. if you can count something, like with endinggs of 1, ..., why not use an array? – Nina Scholz Mar 25 '20 at 18:27
  • I'm sorry, I don't understand, don't I already use an array to store the coordinates? – EmilSun03 Mar 25 '20 at 18:30
  • yes, you do, but you want the value in individual variables, if i understand you correctly. – Nina Scholz Mar 25 '20 at 18:32
  • ... how about ... `const [ coord1, coord2, coord3, coord4 ] = yAxis.map((y, idx) => ['', y, xAxis[idx]].join(''));` ? – Peter Seliger Mar 25 '20 at 19:22
  • ... and I think the Q should not have been closed that quickly, since the possible A's of the linked thread might not be that helpful to the OP after all. – Peter Seliger Mar 25 '20 at 19:29
  • 1
    @PeterSeliger, yes, and no. yes, because this approach assigns directly (i have used this pattern as well, somwhere) and no because op's use of single variable like an array, it should be treated as an array. even the accepted answer is imho wron, as well as the duplicate target. if you like to supply an aswer, i could remove the duplicate closing. – Nina Scholz Mar 25 '20 at 21:29
  • @NinaScholz ... do you mean same approach different assignment ?.. something like this ... `const coordinatesList = yAxis.map((y, idx) => ['', y, xAxis[idx]].join(''));` ... and that's it? If this somehow is an approach the OP was looking for then I'd take the chance of providing this comment as a real answer. – Peter Seliger Mar 25 '20 at 21:38
  • @PeterSeliger, i mean you first comment `const [ coord1, coord2, coord3, coord4 ] = yAxis.map ...`. – Nina Scholz Mar 25 '20 at 21:47

3 Answers3

1

Arrays in Javascript has only indices not names, that's why you need Object:

yAxis = [10, 10, 9, 9];
xAxis = [4, 4, 5, 5];
coordinatesArray = ['coordinate1', 'coordinate2', 'coordinate3', 'coordinate4'];

function test(a, b, c){
    let arrOfObj = [];
    for(let i=0; i < a.length; i++){
        let obj = {};    
        obj[a[i]] = [b[i], c[i]];
        arrOfObj.push(obj);
    }
    return arrOfObj;
}

console.log(test(coordinatesArray,yAxis,xAxis));
Leonid
  • 766
  • 4
  • 8
0

So this is what you're trying to do...

yAxis = [10, 10, 9, 9];
xAxis = [4, 4, 5, 5];

coordinate1 = "magic";
coordinate2 = "will";
coordinate3 = "happen";
coordinate4 = "here";

function test(a, b, c) {
  for(x = 0; x < 4; x++){
    window[a[x]] = "" + b[x] + c[x];
  }
}

function log(a) {
  let output = [];
  for(x = 0; x < 4; x++){
    output.push(window[a[x]]);
  }
  console.log(output);
};

coordinatesArray = ["coordinate1", "coordinate2", "coordinate3", "coordinate4"];

log(coordinatesArray);
test(coordinatesArray, xAxis, yAxis);
log(coordinatesArray);

...but the comments at your question are trying to say that you don't need the variables coordinate1, coordinate2 etc, you can just ALWAYS use one array, like this:

yAxis = [10, 10, 9, 9];
xAxis = [4, 4, 5, 5];

coordinatesArray = ["magic", "will", "happen", "here"];

function test(a, b, c) {
  for(x = 0; x < 4; x++){
    a[x] = "" + b[x] + c[x];
  }
}

console.log(coordinatesArray);
test(coordinatesArray, xAxis, yAxis);
console.log(coordinatesArray);

right?

Stratubas
  • 2,939
  • 1
  • 13
  • 18
  • it looks like it is what I want to do :D! but I'm not familiar with what window is? – EmilSun03 Mar 25 '20 at 18:36
  • when you store them as strings in the array, it looks like they still have values? For example coordinate1 is first == "magic" and then coordinate1 == 410? How does this work? – EmilSun03 Mar 25 '20 at 18:40
  • @EmilSun03 Most things in JavaScript are objects. When you do `myVar = 5`, this `myVar` becomes a property of a pre-existing object that is `window`. If you want better control, you can do something like `const myContainer = {}` and then `myContainer.myVar = 5`, so you will not mess with `window` at all. – Stratubas Mar 25 '20 at 18:43
  • oh okay so with window you're just using an already existing object instead of making a new object? – EmilSun03 Mar 25 '20 at 18:45
  • @EmilSun03 Yes, but try to avoid it. Pretend you don't know about `window` for now. If your variables were of different nature (say `name` and `age`), you would do `const person = {}; person.name = "Stratubas"; person.age = 30;`, but since your variables are array-ish (`myVar1`, `myVar2`...), it's more logical to use an array for them. – Stratubas Mar 25 '20 at 18:49
0

To me it looks like the OP asks for a simple object based key value store. But I might have gotten this wrong.

Thus the answer first puts the focus on how to generate a list of concatenated pairs of x-y coordinates, which in my opinion is the most pragmatic approach ...

const yAxis = [10, 10, 9, 9];
const xAxis = [4, 4, 5, 5];

const coordinatesList = yAxis.map((y, idx) => `${ y }${ xAxis[idx] }`);

console.log('(...coordinatesList) =>', coordinatesList);
.as-console-wrapper { max-height: 100%!important; top: 0; }

If one is not in need of assigning the list's coordinate values, each to a variable-name that could not already be generically created, this list already is a good enough storage.

On the other hand, a destructuring assignment of such a list allows the creation of tailored variables exactly within the scope that is needed (the example code of this approach does also refactor the mapping function from the first provided example) ...

function concatinateCorrespondingBoundArrayItem(partial, idx) {
  return [partial, this[idx]].join('');
}
const yAxis = [10, 10, 9, 9];
const xAxis = [4, 4, 5, 5];

const [
  foo,
  bar,
  baz,
  biz
] = yAxis.map(concatinateCorrespondingBoundArrayItem, xAxis);

console.log('foo bar baz biz :', foo, bar, baz, biz);
.as-console-wrapper { max-height: 100%!important; top: 0; }

Finally, the storage the OP might have asked for, has to be object/map based. A possible approach could then look similar to this last provided example ...

function createCoordinateRecord(collector, coordinateName, idx) {
  collector.storage[coordinateName] = [
    collector.yCoordList[idx],
    collector.xCoordList[idx]
  ].join('');
  return collector;
}
const yAxis = [10, 10, 9, 9];
const xAxis = [4, 4, 5, 5];

const coordinateNameList = ['foo', 'bar', 'baz', 'biz']

const coordinatesMap = coordinateNameList.reduce(createCoordinateRecord, {

  xCoordList: xAxis,
  yCoordList: yAxis,
  storage: {}

}).storage;

console.log('coordinatesMap :', coordinatesMap);

console.log('coordinatesMap.foo :', coordinatesMap.foo);
console.log('coordinatesMap.bar :', coordinatesMap.bar);
console.log('coordinatesMap[coordinateNameList[2]] :', coordinatesMap[coordinateNameList[2]]);
console.log('coordinatesMap[coordinateNameList[3]] :', coordinatesMap[coordinateNameList[3]]);

console.log('Object.keys(coordinatesMap) :', Object.keys(coordinatesMap));
console.log('Object.values(coordinatesMap) :', Object.values(coordinatesMap));
console.log('Object.entries(coordinatesMap) :', Object.entries(coordinatesMap));
.as-console-wrapper { max-height: 100%!important; top: 0; }
Peter Seliger
  • 11,747
  • 3
  • 28
  • 37