How to use the shuffle function from underscore

Find comprehensive JavaScript underscore.shuffle code examples handpicked from public code repositorys.

underscore.shuffle is a function in the Underscore.js library that returns a new shuffled copy of an input array.

362
363
364
365
366
367
368
369
370
371
372
373
f.randmap = function(ar){


    if(!ar) return null
    if(!ar.length) return null


    //ar = _.shuffle(ar)
    
    
    ar = _.sortBy(ar, (r) => {return - Number(r.probability || 0) })

fork icon33
star icon58
watch icon7

+ 5 other calls in file

239
240
241
242
243
244
245
246
247
248
/**
 * Shuffles the deck, emitting an event and displaying a message in chat
 */
shuffleDeck() {
    this.game.emitEvent('onDeckShuffled', { player: this });
    this.deck = _.shuffle(this.deck);
}

/**
 * Takes a decklist passed from the lobby, creates all the cards in it, and puts references to them in the relevant lists
fork icon9
star icon10
watch icon1

How does underscore.shuffle work?

The underscore.shuffle function generates a new array containing the elements of the input array in a randomly shuffled order. The shuffle is performed using the Fisher-Yates algorithm, which iterates over the array from the end to the start, swapping the current element with a random element before it. This ensures that each element has an equal chance of being placed at any position in the shuffled array. The underscore.shuffle function takes one argument, which is the input array to be shuffled. It creates a new array and iterates over the input array using a for loop, swapping each element with a randomly selected element in the array before it. The shuffled array is then returned. Note that underscore.shuffle does not modify the input array, and instead returns a new shuffled array.

2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
// The internal `guard` argument allows it to work with `map`.
_.sample = function(obj, n, guard) {
  if (arguments.length < 2 || guard) {
    return obj[_.random(obj.length - 1)];
  }
  return _.shuffle(obj).slice(0, Math.max(0, n));
};

// An internal function to generate lookup iterators.
var lookupIterator = function(value) {
fork icon0
star icon2
watch icon0

409
410
411
412
413
414
415
416
417
418
    projectIds,
  },
  'found projects'
)
const jobs = []
projectIds = _.shuffle(projectIds) // randomise to avoid hitting same projects each time
const selectedProjects =
  limit < 0 ? projectIds : projectIds.slice(0, limit)
for (projectId of Array.from(selectedProjects)) {
  ;(projectId =>
fork icon0
star icon0
watch icon202

+ 5 other calls in file

Ai Example

1
2
3
4
5
6
const _ = require("underscore");

const myArray = [1, 2, 3, 4, 5];
const shuffledArray = _.shuffle(myArray);

console.log(shuffledArray); // Example output: [3, 1, 5, 2, 4]

In this example, underscore.shuffle is used to shuffle the myArray array. The shuffled array is then logged to the console using console.log.