简体   繁体   中英

How do I take first value of sub-array in an array?

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)

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

 }

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

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

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)

Same Using forEach:

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

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

console.log(lats)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM