Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 306
petrichor Avatar asked Sep 12 '25 21:09

petrichor


2 Answers

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];
}
like image 64
loganfsmyth Avatar answered Sep 15 '25 10:09

loganfsmyth


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]]
like image 35
Darin Dimitrov Avatar answered Sep 15 '25 12:09

Darin Dimitrov