-1

I'm trying to define an array which works this way:

myArray[0] = 'Volkswagen'
myArray[0][0] = 'Crossfox'
myArray[1] = 'Ford'
myArray[1][0] = 'Focus'

I can do by hand but of course it's not the way to do it. I have a simple array with this:

arrayVolks = ['Crossfox', 'Up', 'Golf'];
arrayVolks[name] = 'Volkswagen';

My problem is that I don't know how to create the first array with the index with the name of the array and then add the array.

I was thinking on some way like this:

var myArray = [ arrayVolks[name]: {arrayVolks} ] 

(The code immediately over it's more like a pseudo code than actual javascript)

Is it possible?

Thank you in regards

Yacomini
  • 157
  • 1
  • 13

2 Answers2

1

you can't create array like this in javascript:

myArray[0] = 'Volkswagen'
myArray[0][0] = 'Crossfox'
myArray[1] = 'Ford'
myArray[1][0] = 'Focus'

how about using Object instead?

var obj = {};
obj['Volkswagen'] = ['Crossfox', 'Up', 'Golf'];
obj['Ford'] = ['Focus'];

// get all brands
console.log(Object.keys(obj));

// print all "Volkswagen"
console.log(obj['Volkswagen']);
console.log(obj.Volskwagen);
pwolaq
  • 5,937
  • 16
  • 43
  • Am i being able to use the Object.keys(obj).length? I know it works, but is it the correct way of doing it? (to access the length) – Yacomini Aug 17 '16 at 14:03
  • According to this: http://stackoverflow.com/a/4889658/2048417 - yes. But be advised that `Object.keys` doesn't work in IE9. – pwolaq Aug 17 '16 at 14:13
1

A jagged array is an array of arrays.

By doing myArray[0] = 'Volkswagen' you set the first element of the root array to a string so you are violating the structure already.

An alternate data structure would probably be better, but if you wish to have a jagged array you may define a structure where the first element of each nested array is the make while the other elements will be the models.

var cars = [
    ['Volkswagen', 'Crossfox'],
    ['Ford', 'Focus']
];

console.log(cars[0][0]); //Volkswagen
console.log(cars[0][1]); //Crossfox
plalx
  • 39,329
  • 5
  • 63
  • 83