samedi 23 avril 2016

Javascript - how to pick random elements from an array in order?

I have an array

var numbers = ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18"];

and trying to get random items from it, so:

console.log(_.sample(numbers, 5));

this will give me 5 random numbers (strings) from the array in a random order, like:

"17", "2", "3", "18", "10"

How do I get a sorted list or random items, like?

"2", "3", "10", "17", "18"

_.sample will probably not be the best choice here. I am trying to get random items from a given array and have these items picked up from left to right of the array.

How to do this in javascritp?

Thank you.

EDIT: I have an array of strings, not numbers, so I cannot sort the randomly picked items.

EDIT2: To avoid confusing, in the array are words (= strings), I used there numbers as strings to more easily demonstrate what I am trying to achieve. (sorry for possible confusions)




Aucun commentaire:

Enregistrer un commentaire