Reputation: 131
I am struggeling with my multidimensional array. I actually have done research for a few hours but couldn't find anything helpful.
I have a multidimensional array which looks like this:
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4, 0],
['Coogee Beach', -33.923036, 151.259052, 1, 1],
['Cronulla Beach', -34.028249, 151.157507, 3, 2],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2, 0],
['Maroubra Beach', -33.950198, 151.259302, 5, 2]
];
Now I want to add something to the array with push like:
locations.push( DATA HERE ); // 'Cronulla Beach 2', -34.028249, 151.157507, 8, 7
Which should look like this at the end:
var locations = [
['Bondi Beach', -33.890542, 151.274856, 4, 0],
['Coogee Beach', -33.923036, 151.259052, 1, 1],
['Cronulla Beach', -34.028249, 151.157507, 3, 2],
['Manly Beach', -33.80010128657071, 151.28747820854187, 2, 0],
['Maroubra Beach', -33.950198, 151.259302, 5, 2],
['Cronulla Beach 2', -34.028249, 151.157507, 8, 7]
];
Note: I need an array, so it doesn't help me if it is a solution with an object.
Preferably the solution should also work if the array is still empty like locations[];
Upvotes: 1
Views: 91
Reputation: 6404
Just put the contents in another array and push that into your locations
array, like
locations.push(['Cronulla Beach 2', -34.028249, 151.157507, 8, 7]);
Upvotes: 1
Reputation: 738
Since a multidimensional array is just an array of arrays, and you can create a new array by just placing a list of objects in square brackets, you can do this:
locations.push(['Cronulla Beach 2', -34.028249, 151.157507, 8, 7]);
To access or edit an existing location, use its index:
var location = locations[0];
console.log(location);
locations[0][0] = "Bomba Beach"; // change name of first location
locations[0][1] = -30.2; // change latitude of first location
Upvotes: 2