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.
-
3What's wrong with for-loops?Veger– Veger2012年12月29日 16:15:50 +00:00Commented Dec 29, 2012 at 16:15
-
where's the connection to json?!bukart– bukart2012年12月29日 16:17:36 +00:00Commented Dec 29, 2012 at 16:17
-
@Veger Nothing wrong. I'm coming from MATLAB background. That's why I look for non-loop solution I think.petrichor– petrichor2012年12月29日 16:17:59 +00:00Commented Dec 29, 2012 at 16:17
-
1Loops in JavaScript are not evil :)Veger– Veger2012年12月29日 16:19:37 +00:00Commented Dec 29, 2012 at 16:19
-
see below, there's a loop free way: stackoverflow.com/questions/14083524/…bukart– bukart2012年12月29日 16:32:52 +00:00Commented Dec 29, 2012 at 16:32
2 Answers 2
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];
}
Comments
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]]