-2

I have JS array with coordinates:

    var markers = xmlDoc.documentElement.getElementsByTagName("marker");
    var waypoints = new Array();

    for (var i = 0; i < markers.length; i++) {
        point = new google.maps.LatLng(
        parseFloat(markers[i].getAttribute("lat")),
        parseFloat(markers[i].getAttribute("lon")));

        waypoints.push({location: point, stopover: false});
   }

I need to filter array and leave only 8 random values in it, if array length is > 8.

Thank you for the help.

DeividasJJ
  • 125
  • 1
  • 13

2 Answers2

2

To solve this you'll need to be able to create a random integer between 0 and length - 1, and then Array.prototype.splice out the item at that index in a loop until you reach your desired length.

function randInt(max, min) {
    return ((min | 0) + Math.random() * (max + 1)) | 0;
}

function remRandom(arr, newLength) {
    var a = arr.slice();
    while (a.length > newLength) a.splice(randInt(a.length - 1), 1);
    return a;
}

var foo = ['a', 'b', 'c', 'd', 'e', 'f'];
remRandom(foo, 3); // e.g. ["b", "c", "e"]
Paul S.
  • 64,864
  • 9
  • 122
  • 138
  • If you're creating a new array anyway, it would be much easier to *select* 8 values than to take all and remove every but 8 ones. – Bergi Aug 21 '13 at 11:56
  • @Bergi I created a new array because I don't like side effects most of the time. Choosing non-repeating random numbers would require more logic too (easiest way is shuffle, but looked like OP wanted to preserve order). I don't like repeatedly guessing random numbers until finding an okay one, what happens if you want to choose `999` random items of `1000` using those methods? I'm sure there are some good algorithms out there. Anyway; whether it matters depends on how big the _Array_ is expected to get. For a big array I'll agree, that would be better. – Paul S. Aug 21 '13 at 12:04
  • Thank you very much, working as expected ;) – DeividasJJ Aug 21 '13 at 12:11
1

I would use a mixture of javascript's random function and the splice method for arrays. Do it for the number of times that the array is greater than 8.

http://www.w3schools.com/jsref/jsref_splice.asp

http://www.w3schools.com/jsref/jsref_random.asp

you could remove one element from a random position within the array by generating a number between 0 and array.length - 1 then use splice to cut that element from the array. See this answer for the removal of an element:

How do I remove a particular element from an array in JavaScript?

Community
  • 1
  • 1
Richard
  • 21,728
  • 13
  • 62
  • 101