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?
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)
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)
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);
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)