1

I have a two-dimensional array of latitudes and longitudes as below -

arrLoc = [
       [18.3, 70.2],
       [20.5, 75.4],
       [19.3, 50.7],
       [14.9, 40.5],

      ..... and so on, up to 10 items

I want to pick up a random lat-long from this array, for my further coding.

How to get a random item from this two-dimensional array?

Alexander Ciesielski
  • 10,506
  • 5
  • 45
  • 66
NetYogi
  • 243
  • 5
  • 11
  • That's for single-dimensional array. Won't work. I don't want to involve jQuery. – NetYogi Dec 10 '16 at 13:56
  • Your `arrLoc` is not an `Array` but looks more like an `Object` although wrong syntax. The answer there is `javascript` and doesn't involve `jQuery`. May be give the exact value of `arrLoc` here. – sabithpocker Dec 10 '16 at 13:58
  • the question and code does not make any sense! – Amir Koklan Dec 10 '16 at 13:59
  • @NetYogi, please update your code Snippet to some valid JS – Thomas Dec 10 '16 at 14:08
  • 1
    @NetYogi, this ain't really a two-imensional Array, logically it is a one-dimensional Array of Coordinates. Just that your coordinates are representad by an Array instead of an Object. `[18.3, 70.2]` instead of `{lat: 18.3, lng: 70.2}`. Take another look at [how to get a random Value from an Array](http://stackoverflow.com/questions/4550505/getting-random-value-from-an-array) – Thomas Dec 10 '16 at 14:40
  • @Thomas Why should this not be valid? It's an array of arrays - [2 dim. array on SO](http://stackoverflow.com/a/966234/1456318) – michaPau Dec 10 '16 at 15:04
  • @michaPau now it is valid, and clear what we deal with, but take a look at the [edit-history](http://stackoverflow.com/posts/41076246/revisions). – Thomas Dec 10 '16 at 15:05

1 Answers1

1

To get random values from your arrLoc definition just use Math.random

var arrLoc = [
       [18.3, 70.2],
       [20.5, 75.4],
       [19.3, 50.7],
       [14.9, 40.5]
  ];

  //random pair
  var randIndex = Math.floor(Math.random() * arrLoc.length);
  console.log("Latitude:"+arrLoc[randIndex][0]+", Longitude:"+arrLoc[randIndex][1]);

  //two random values
  var rand1 = Math.floor(Math.random() * arrLoc.length);
  var rand2 = Math.floor(Math.random() * arrLoc.length);
  console.log("Latitude:"+arrLoc[rand1][0]+", Longitude:"+arrLoc[rand2][1]);

No need to accept it as an answer, Stack overflow has already answers for this

michaPau
  • 1,598
  • 18
  • 24
  • `Math.floor()` + `arrLoc.length-1` is wrong, this would never select the last item in the Array. `Math.floor( Math.random() * arrLoc.length )` – Thomas Dec 10 '16 at 15:09
  • Yes , thanks, it's updated – michaPau Dec 10 '16 at 15:13
  • Thanks @michaPau, @Thomas! The first code snippet (random pair) worked for me. The second one (two random pairs), as named, gives random values from different cells. – NetYogi Dec 10 '16 at 16:43