1

If I have an array of strings like stringsArray = ["arrOne","arrTwo","arrThree"] and a list of arrays like var arrOne = [], arrTwo = [], arrThree = [] is it possible to do something like:

stringsArray = ["arrOne","arrTwo","arrThree"]
var arrOne = [], arrTwo = [], arrThree = []

stringsArray[0].push(somestuff)

to basically push something into arrOne in this case

m4tt
  • 825
  • 1
  • 11
  • 28
  • It's not clear what you're trying to do. Are you trying to push something into arrOne in that example? – Tom Roman Mar 10 '21 at 14:33
  • @TomRoman Yes, exactly. i'll update – m4tt Mar 10 '21 at 14:34
  • Where do the strings in `stringsArray` come from? Who decides what the variable names are called? Currently, it looks like you simply need `const stringsArray = [[], [], []];`. If you don’t know the strings in advance, use an object like `const arrays = { arrOne: [], arrTwo: [], arrThree: [] };` and `arrays[stringsArray[0]].push`. – Sebastian Simon Mar 10 '21 at 14:39

3 Answers3

2

As an alternative Maybe you can achieve it with Object.

const stringsArray = ["arrOne","arrTwo","arrThree"]
// var arrOne = [], arrTwo = [], arrThree = []
// stringsArray[0].push(somestuff)
const obj = stringsArray.reduce((acc, str)=>{
  acc[str] = [];
  return acc;
}, {});

obj[stringsArray[0]].push("SomeStuff");
obj["arrTwo"].push("someStuff!");
obj.arrThree.push("Threee");
console.log(obj);
kyun
  • 9,710
  • 9
  • 31
  • 66
1

You could take an object as reference to the arrays.

const
    stringsArray = ["arrOne","arrTwo","arrThree"],
    arrOne = [], arrTwo = [], arrThree = [],
    reference = { arrOne, arrTwo, arrThree };
    

reference[stringsArray[0]].push('somestuff');

console.log(arrOne);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

Going off the code you have given, you're trying to push into arrOne by pushing into the stringsArray. Your best bet is to do something like:

stringsArray = [[],[],[]]

stringsArray[0].push(somestuff)

You could then access this with something like:

let arrOne = [...stringsArray[0]]
Tom Roman
  • 125
  • 1
  • 8