0

My goal is to create an array that look something like this

var locations = [
    [
        "New Mermaid",
        36.9079,
        -76.199
    ],
    [
        "1950 Fish Dish",
        36.87224,
        -76.29518
    ]
]; 

I've tried

var data = $locations;
var locations = [];

for (i = 0; i < data.length; i++) {

  locations[i] =
  data[i]['name']+','+
  data[i]['lat']+','+
  data[i]['lng'];

}

console.log(locations);

I've got

["Apple  HQ,33.0241101,39.5865834", "Google MA,43.9315743,20.2366877"]

However that is not the exact format.


I want

var locations = [
    [
        "New Mermaid",
        36.9079,
        -76.199
    ],
    [
        "1950 Fish Dish",
        36.87224,
        -76.29518
    ]
];

How do I update my JS to get something like that ?

8
  • 1
    Why do you want an array that contains arrays that each contain 1 string? Commented Feb 1, 2016 at 19:17
  • 2
    That is not an object. An object would be: {company: 'Apple HQ', lat: '33.024', long: '39.586'}. Commented Feb 1, 2016 at 19:20
  • Sorry, I might have upload the wrong format. I updated my post. Thanks for poiting that out. Commented Feb 1, 2016 at 19:20
  • Provide your expected output Commented Feb 1, 2016 at 19:21
  • You want an array of arrays. Build the array first, then append it to your master array. Commented Feb 1, 2016 at 19:21

2 Answers 2

3

To build an "Array of arrays", this is one (of a few different methods):

for (i = 0; i < data.length; i++) {
  locations[i] = [];
  locations[i][0] = data[i]['name'];
  locations[i][1] = data[i]['lat'];
  locations[i][2] = data[i]['lng'];
}

or

for (i = 0; i < data.length; i++) {
  locations[i] = [data[i]['name'], data[i]['lat'], data[i]['lng']];
}
Sign up to request clarification or add additional context in comments.

Comments

3
var locations = data.map(function(location){
  return [ location.name, location.lat, location.lng ];
}

Map will make an array with all the returned values from your function. Each return will be an array consisting of the 3 attributes you are looking for.

2 Comments

Very nice! Great solution.
Rather this: return [ location.name, location.lat, location.lng ];

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.