1

Let's say my nested array is in the format [latitude, longitude] and the array that I want to input is [[10,20],[30,40],[50,60]].

I want to return an array of only latitudes so [10, 30, 50] Now how do I do this in JavaScript?

8 Answers 8

4

You could use the .map() method like so:

var array = [[10,20],[30,40],[50,60]];

var result = array.map(item => item[0]);

console.log(result)

Sign up to request clarification or add additional context in comments.

1 Comment

This is how you do it, for loops are not.
2

Another way to get the same result;

const arr = [[10,20],[30,40],[50,60]];
const latitudes=[];
for (let i = 0; i < arr.length; i++){
   const arr1 = arr[i];

  latitudes.push(arr1[0]); 

 }

Comments

1

Support in : Chrome(yes) , Firefox(yes), IE5.5+ ,O(yes),Safari(yes)

var arr = [[10,20],[30,40],[50,60]] ;
var i = 0 , res = [] ;

while (i < arr.length ) {
  res.push(arr[i][0]) ;
  i++ ;
}

console.log (res) ;

Comments

1

With ES6 you can also use destructuring & map to get it to this:

var arr = [[10,20],[30,40],[50,60]];

var result = arr.map(([a]) => a)

console.log(result)

Comments

0

You can use array#map with array#destructuring to get the first index item from the individual array.

var locations = [[10,20],[30,40],[50,60]],
    latitudes = locations.map(([latitude]) => latitude);
console.log(latitudes)

Comments

0

You can do it by reduce too.

let obj = [[10,20],[30,40],[50,60]];

const newArr = obj.reduce((nArr, lat) => {
  nArr.push(lat[0]);
  return nArr;
}, []);

console.log(newArr);

Comments

0

You have quite a number of looping mechanisms to choose from. The most straightforward is a map since you expect an array as a result. Using destructuring assignment simplifies the naming, but there is more magic going on and it is ES6-heavy, so keep that in mind if cross-browser compliance is a concern.

let log = console.log
let arr = [[10,20],[30,40],[50,60]]

// Destructuring Assignment
let ex1 = arr.map(([lat,long])=>lat) 
log('ex1:',ex1)

// Non-Destructuring
let ex2 = arr.map(set=>set[0])
log('ex2:',ex2)

// Reduce
let ex3 = arr.reduce((ar,val)=>(ar.push(val[0]),ar),[])
log('ex3:',ex3)

Of course you could get creative and flatten the array and use math to cherry-pick your values:

let arr = [[10,20],[30,40],[50,60]]
let ex4 = arr.flat().filter((v,i)=>!(i%2))
console.log('ex4:',ex4)

Comments

0

Same Using forEach:

let latLongs = [[10, 20], [30, 40], [50, 60]]

let lats = []
latLongs.forEach(
    (latLong) => {
      lats.push(latLong[0])
    }
)

console.log(lats)

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.