Introduction
Creating a multidimensional array in JavaScript can be a great way to store and organize data. A multidimensional array is an array that contains other arrays as its elements. This type of array can be used to store data in a hierarchical structure, such as a list of products and their associated prices. In this tutorial, we will discuss how to create a multidimensional array in JavaScript and how to access and manipulate its elements. We will also discuss some of the common methods used to work with multidimensional arrays. By the end of this tutorial, you will have a better understanding of how to create and work with multidimensional arrays in JavaScript.
Solution
// Option 1:
let multiArray = [[1,2,3], [4,5,6], [7,8,9]];
// Option 2:
let multiArray = [];
multiArray[0] = [1,2,3];
multiArray[1] = [4,5,6];
multiArray[2] = [7,8,9];
I asked you to use console.log()
on the input object, because that will make it clear what you problem is:
// your (wrong) way
const indexe = 5;
const yourway = {
indexe: {
"input_name": 'value' // I used a string so I wouldn't have to import jQuery for this
},
};
console.log('Your original version: ', yourway);
// using a real array, this will have a lot of undefined elements
const arrayV = [];
arrayV[indexe] = {
"input_name": 'value'
}
console.log('Array version: ', arrayV);
// using an object correctly
const objectV1 = {
[indexe]: {
"input_name": 'value'
},
};
console.log('Object version: ', objectV1);
// you can add more to it like so:
objectV1[7] = {
"input_name": 'value'
};
console.log('After adding another entry: ', objectV1);
// you also don't need to create a new object with an already existing element. This will suffice:
const objectV2 = {};
objectV2[indexe] = {
"input_name": 'value'
};
console.log('2. Object version: ', objectV2);
// imortant note on the object versions: length is not defined for objects
console.log('Object version 1 length: ', objectV1.length);
console.log('Object version 2 length: ', objectV2.length);
Your problem simply was that it didn’t use the value of indexe
, but rather that as the name of a property. I have also included the array version, even though that is not an associative array (and as people in the comments have pointed out, neither are the object versions, really).
P.s. I used ES6 Syntax. It is rather widely supported, but I would still recommend going for at least ES5. (There are pre-processors for that)
If you want to make it ES5-valid, replace const
with var
and don’t use the objectV1
-version.
solved creating a multidimensional array javascript