0

I have an array that contains a set of arrays, I want to reach the inside arrays variable names like;

     var mainArr = [
             arr1 = ["1","2","3"],
             arr2 = ["4","5","6"],
             arr3 = ["7","8","9"],
                   ];

I want to print arr1, arr2, arr3.

Note that I'm using Javascript Ecma 5

3
  • You could use objects if you want key value pairs. Otherwise mainArr[0], mainArr[1] and mainArr[2] will get you elements on each index. Commented Feb 27, 2020 at 7:05
  • This isn't correct way of creating a 2D Array. it should be something like var mainArr = [["1", "2", "3"], ["4", "5", "6"]] and then you can access element of array using it's index. Commented Feb 27, 2020 at 7:09
  • I dont know if it is ES5 where you can call your object as mainArr['arr1'] if so you can call your array dynamically like mainArr['arr' + index] Commented Feb 27, 2020 at 7:10

3 Answers 3

1

What you're asking is actually a JavaScript Object.

const obj = {
    arr1: ['1','2','3'],
    arr2: ['4','5','6'],
    arr3: ['7','8','9']
}

You can access "properties" of this object like obj['arr1'] etc.

To get property names you can use: Object.getOwnPropertyNames(obj). It'll return an array of keys (['arr1', 'arr2', 'arr3']).

Sign up to request clarification or add additional context in comments.

1 Comment

I don't want the values, I want the variable names, thanks
1

You need to store each array inside mainArr as an object like {arr1: ["1","2","3"]}.

And after you can loop through mainArr and print the key value of each element, like.

mainArr = [
 {arr1: ["1","2","3"]},
 {arr2: ["4","5","6"]},
 {arr3: ["7","8","9"]},
];
mainArr.forEach(arr => console.log(Object.keys(arr)))

This will print all arrays inside the mainArr.

Comments

0

You are actually handling it the wrong way. The best way to do this by not pushing an array using Array.push() method. instead do this by using named indexed Array, because by default arrays have index as numbers i.e., 0,1,2,3,..

var myArray = [];

myArray["arr1"] = ["1","2","3"];

myArray["arr2"] = ["4","5","6"];

myArray["arr3"] = ["7","8","9"];

console.log(myArr); => 
 [arr1: Array(3), arr2: Array(3), arr3: Array(3)]
   arr1: (3) ["1", "2", "3"]
   arr2: (3) ["4", "5", "6"]
   arr3: (3) ["7", "8", "9"]    

console.log(Object.keys(myArray)); => ["arr1","arr2","arr3"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.