petrichor
petrichor

Reputation: 6569

How to extract values from an array of arrays in Javascript?

I have a variable as follows:

var dataset = {
"towns": [
    ["Aladağ", "Adana", [35.4,37.5], [0]],
    ["Ceyhan", "Adana", [35.8,37], [0]],
    ["Feke", "Adana", [35.9,37.8], [0]]
    ]
};

The variable has a lot of town data in it. How can I extract the first elements of the third ones from the data efficiently? I,e, what will ... be below?

var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data 

And what to do if I want to store both values in the array? That is

var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data 

I'm very new to Javascript. I hope there's a way without using for loops.

Upvotes: 4

Views: 39738

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039408

Impossible without loops:

var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
    myArray.push(dataset.towns[i][2][0]);
}
// at this stage myArray = [35.4, 35.8, 35.9]

And what to do if I want to store both values in the array?

Similar, you just add the entire array, not only the first element:

var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
    myArray.push(dataset.towns[i][2]);
}
// at this stage myArray = [[35.4,37.5], [35.8,37], [35.9,37.8]]

Upvotes: 2

loganfsmyth
loganfsmyth

Reputation: 161617

On newer browsers, you can use map, or forEach which would avoid using a for loop.

var myArray = dataset.towns.map(function(town){
  return town[2];
});
// myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]]

But for loops are more compatible.

var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
  myArray.push(dataset.towns[i][2];
}

Upvotes: 8

Related Questions