-4

I have an array of array data. I want to loop array of array value and get the first values of each array.

var myArr= [
 ["1",10],
 ["2",20],
 ["3",34]
]

I need to get the first value of each array. Here first value is a string value. How to get "1","2","3" these string value using loop.

2 Answers2

0

var myArr= [
 ["1",10],
 ["2",20],
 ["3",34]
]

console.log(myArr.map(item=>item[0]));

You could use map function. This will return an array containing only the first values of each array in the main array.

Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

samuellawrentz
  • 1,662
  • 11
  • 23
  • 1
    He doesn't need a map. He just needs to loop over the first, and only, element in the outer most array. A simple search engine attempt at "loop over an array in javascript" would tell him how to do this. – Taplar Jul 25 '18 at 15:10
  • Agreed! Just wanted to show the capabilities of array functions in Javascript :) – samuellawrentz Jul 25 '18 at 15:12
0

to iterate over an array and just do an action with it you can use .forEach if you would like to iterate over an array and return a new array you can use .map

in this case to just log the first item of each sub array you can

myArr.forEach(x => console.log(x[0])
theya
  • 33
  • 2
  • 8