How to use the shuffle function from lodash

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

lodash.shuffle is a function that randomly shuffles the elements in an array and returns a new array with the shuffled elements.

4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
 * @category Collections
 * @param {Array|Object|string} collection The collection to shuffle.
 * @returns {Array} Returns a new shuffled collection.
 * @example
 *
 * _.shuffle([1, 2, 3, 4, 5, 6]);
 * // => [4, 1, 6, 3, 5, 2]
 */
function shuffle(collection) {
  var index = -1,
fork icon73
star icon711
watch icon29

240
241
242
243
244
245
246
247
248
249
const students = [];
const resultList = await sqldb.queryAsync(sql.select_enrollments, aid);
resultList.rows.forEach((element) => {
  students.push(element.user_list);
});
_.shuffle(students);
var numStudents = resultList.rowCount;
var notAssigned = [];
const resultList2 = await sqldb.queryAsync(sql.select_not_assigned, aid);
resultList2.rows.forEach((element) => {
fork icon253
star icon252
watch icon0

How does lodash.shuffle work?

lodash.shuffle takes an array as input and returns a new array with the same elements, but in a shuffled order. The shuffling is performed using the Fisher-Yates shuffle algorithm, which works by iterating over the array from the last element to the first and swapping each element with a randomly chosen element from the remaining unshuffled elements.

The function can be called with an optional options object that allows the user to specify a random seed to ensure reproducibility of the shuffle, and also to limit the number of shuffles performed.

The original array is not modified, and the shuffled array is returned as the result of the function call.

338
339
340
341
342
343
344
345
346
347
module.exports.selectKeys          = _.selectKeys;
module.exports.seq                 = _.seq;
module.exports.set                 = _.set;
module.exports.setPath             = _.setPath;
module.exports.setWith             = _.setWith;
module.exports.shuffle             = _.shuffle;
module.exports.size                = _.size;
module.exports.slice               = _.slice;
module.exports.slugify             = _.slugify;
module.exports.snakeCase           = _.snakeCase;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

555
556
557
558
559
560
561
562
563
564
try {
  Object.assign(this, { addBots, useTimer, timerLength, shufflePlayers });
  this.renew();

  if (shufflePlayers) {
    this.players = shuffle(this.players);
  }

  if (this.shouldAddBots()) {
    const burnsPerPack = this.type === "cube draft"
fork icon61
star icon95
watch icon0

Ai Example

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

const array = [1, 2, 3, 4, 5];

const shuffledArray = _.shuffle(array);

console.log(shuffledArray); // Output: [3, 2, 4, 1, 5] or any other shuffled order

In the above example, lodash.shuffle is used to shuffle the array by returning a new array with its elements shuffled randomly. The original array remains unchanged. The shuffled array is assigned to the shuffledArray variable, and then logged to the console using console.log.

186
187
188
189
190
191
192
193
194
    forgetIfNotUsing()

}

self.similarnodes = function(node, count){
    var withrating = _.shuffle(self.initednodeswithrating())
    var i = 0
    var mylastblock = node.lastblock()
    
fork icon33
star icon58
watch icon7

+ 7 other calls in file

385
386
387
388
389
390
391
392
393
394
} else if (widget.templateData.template.category) {
	topicData = await getCategoryTopics('month', 'votes');
	if (!topicData.length) {
		topicData = await getCategoryTopics('alltime', 'recent');
	}
	topicData = _.shuffle(topicData).slice(0, numTopics + 1);
	topicData = topicData.filter(topic => topic && !topic.deleted);
} else {
	const data = await topics.getTopicsFromSet('topics:recent', widget.uid, 0, numTopics);
	topicData = data ? data.topics : [];
fork icon32
star icon16
watch icon0

189
190
191
192
193
194
195
196
197
 * @param {Playlist} playlist
 * @returns {Promise<Playlist>}
 */
// eslint-disable-next-line class-methods-use-this
async shufflePlaylist(playlist) {
  playlist.media = shuffle(playlist.media);
  await playlist.save();
  return playlist;
}
fork icon12
star icon30
watch icon5

+ 3 other calls in file

15
16
17
18
19
20
21
22
23
24
  this.preserveAlpha = !!options.preserveAlpha;
  this.invert = !!options.invert;
}
set gradient(gradient) {
  if (!gradient) {
    this._gradient = _.shuffle(allGradients())[0];
  } else {
    this._gradient = loadGradient(gradient);
  }
}
fork icon9
star icon5
watch icon3

+ 2 other calls in file

170
171
172
173
174
175
176
177
178
179
async initBeforeSync() {
  this.__rootNetworkAddress = await this.db.getData('rootNetworkAddress');
  let initialNetworkAddress = this.options.initialNetworkAddress || this.address;

  if(Array.isArray(initialNetworkAddress)) {
    initialNetworkAddress = _.shuffle(initialNetworkAddress);
    initialNetworkAddress = initialNetworkAddress.sort(a => a === this.address? 0: -1);
  }
  
  this.initialNetworkAddress = await this.getAvailableAddress(initialNetworkAddress);
fork icon4
star icon14
watch icon4

+ 20 other calls in file

48
49
50
51
52
53
54
55
56
57
58
59
  for (let i = 0; i < nContacts - nIndexed; i++) {
    notIndexedContacts.push(generateFakeContact(i, false))
  }


  let contacts = notIndexedContacts.concat(indexedContacts)
  contacts = shuffle(contacts)


  await client.stackClient.collection('io.cozy.contacts').updateAll(contacts)
}

fork icon13
star icon10
watch icon0

485
486
487
488
489
490
491
492
493
494
},
{
  name: 'sortWith.object',
  params: [obj1, obj10, obj100, obj1000],
  benchmarks: (array) => {
    const shuffled = _.shuffle(array)
    const iirisComparators = [
      I.ascend((obj) => obj.kConstant),
      I.descend((obj) => obj.kConstant),
      I.ascend((obj) => obj.k1),
fork icon1
star icon31
watch icon0

269
270
271
272
273
274
275
276
277
278
279
280
281
console.log(sample); // => 2


const sampleSize = _.sampleSize([1, 2, 3, 4], 2);
console.log(sampleSize); // => [3, 1]


const shuffle = _.shuffle([1, 2, 3, 4]);
console.log(shuffle); // => [4, 1, 3, 2]


const size = _.size([1, 2, 3]);
console.log(size); // => 3
fork icon0
star icon4
watch icon0

+ 15 other calls in file

240
241
242
243
244
245
246
247
248
249
stats.totalRounds++;
saveStats()

var players = games[group_id].playerorder; //get the array of players
var playerobj = games[group_id].players; //associative array of playerid -> player object
_.shuffle(players); //_.shuffle them
var playerz = [];
var numpairstochoose = chance.integer({
    min: 1,
    max: Math.max(Math.floor(players.length / 2), 1)
fork icon0
star icon2
watch icon0

+ 3 other calls in file

49
50
51
52
53
54
55
56
57
58
  emptyHashes,
  oneCharHashes,
  twoCharHashes,
  threeCharHashes
)
const shuffledHashes = _.shuffle(allHashes)

fs.writeFile('2K.hashes.txt', shuffledHashes.join('\n'), (err) => {
  if (err) throw err
  console.log('Hashes saved to 2K.hashes.txt')
fork icon1
star icon0
watch icon0

631
632
633
634
635
636
637
638
639
640
selectedMovies.push(...tagMedia.Movies);
selectedShows.push(...tagMedia.Shows);
items.push(...tagMedia.Movies);
items.push(...tagMedia.Shows);

let shuffledItems = _.shuffle(items);

return {
    "Items": shuffledItems,
    "Movies": selectedMovies,
fork icon0
star icon2
watch icon1

+ 2 other calls in file

78
79
80
81
82
83
84
85
86

combo.push(...commercials);
combo.push(...shorts);
combo.push(...music);

let shuffledCombo = _.shuffle(combo);
let half = Math.ceil(shuffledCombo.length / 2);
let firstHalf = shuffledCombo.slice(0, half);
let secondHalf = shuffledCombo.slice(half);
fork icon0
star icon2
watch icon1

+ 2 other calls in file

42
43
44
45
46
47
48
49
50
51
Promise.all([
    db.sportsman.find({ competitionId: round.competitionId }),
    db.team.find({ competitionId: round.competitionId })
]).then(async ([resSportsmen, resTeams]) => {
    const sportsmen = _.shuffle((resSportsmen || []).filter((item) => item.selected));
    const teams = _.shuffle((resTeams || []).filter((item) => item.selected));

    let group = {
        roundId: round._id,
        competitionId: competition._id,
fork icon1
star icon1
watch icon1

+ 33 other calls in file

95
96
97
98
99
100
101
102
103
104
function sCommonRobotSend ({ target = 'workweixin', alias = '', type = '', data = {}, dataFn = undefined, duration = '', immediately = false, isSkipDayOffDates = false } = {}) {
  // `[飞书消息去重防吞: ${}]`
  const feishuNot = () => {
    const r = generateRndNum(7);
    const iii = generateRndNum(1);
    const prefixs = shuffle([
      '斗智斗勇去重消息',
      '飞书我只是机器人',
      '让我发发消息鸭',
      'ROBOT FOREVER',
fork icon0
star icon1
watch icon0

85
86
87
88
89
90
91
92
93
  );
})
.then(function() {

  //create pack and shuffle cards
  const shuffled = _.shuffle(createPack());

  var cardsP1 = [];
  var cardsP2 = [];
fork icon0
star icon0
watch icon1

54
55
56
57
58
59
60
61
62
63
        returnIds: true,
        timeRange: cutoff !== 0 ? cutoff / 1000 : 0,
        timeFilter: 'newer',
    });
    data.tids = data.tids.filter(_tid => _tid !== tid); // remove self
    return _.shuffle(data.tids).slice(0, 10).map(Number);
}

async function getCategoryTids(tid, cutoff) {
    const cid = await Topics.getTopicField(tid, 'cid');
fork icon0
star icon0
watch icon1

+ 31 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)