4

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.

5
  • 3
    What's wrong with for-loops? Commented Dec 29, 2012 at 16:15
  • where's the connection to json?! Commented 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. Commented Dec 29, 2012 at 16:17
  • 1
    Loops in JavaScript are not evil :) Commented Dec 29, 2012 at 16:19
  • see below, there's a loop free way: stackoverflow.com/questions/14083524/… Commented Dec 29, 2012 at 16:32

2 Answers 2

8

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];
}
Sign up to request clarification or add additional context in comments.

Comments

2

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]]

Comments

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.