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?

7
  • That's for single-dimensional array. Won't work. I don't want to involve jQuery. Commented Dec 10, 2016 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. Commented Dec 10, 2016 at 13:58
  • the question and code does not make any sense! Commented Dec 10, 2016 at 13:59
  • @NetYogi, please update your code Snippet to some valid JS Commented Dec 10, 2016 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 Commented Dec 10, 2016 at 14:40

1 Answer 1

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

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

3 Comments

Math.floor() + arrLoc.length-1 is wrong, this would never select the last item in the Array. Math.floor( Math.random() * arrLoc.length )
Yes , thanks, it's updated
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.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.