Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kristian Woods
23,414 PointsHow can I shuffle items in an array and output it?
const ranArray = [
'foo',
'bar',
'toy',
'car'
];
const genNum = (upper) => {
return Math.floor(Math.random() * upper) + 1;
};
const loopRanArray = (arr) => {
for(items of arr) {
console.log(arr[genNum(3)]);
}
};
loopRanArray(ranArray);
3 Answers
Steven Parker
243,318 PointsPerhaps this is this what you're looking for:
const loopRanArray = arr => {
var copy = arr.slice();
while (copy.length) {
console.log(copy.splice(genNum(copy.length)-1, 1)[0]);
}
};
Or do you need to shuffle the contents in the array? It's the same idea, you still randomly pick items but swap them instead of removing them.
const shuffle = arr => {
for (var i=0; i<arr.length-1; i++) {
var x = i + genNum(arr.length-i)-1;
if (i != x) [arr[i], arr[x]] = [arr[x], arr[i]];
}
};
Kristian Woods
23,414 PointsYeah, sorry, I meant shuffle the contents within the array
Steven Parker
243,318 PointsOK, I expanded my answer to show it both ways.
Kristian Woods
23,414 PointsHey Steven, thanks for getting back to me. I have a few questions though .
Why did you use the var keyword over let.
I don't quite understand what your code is doing. - I'll have a crack at breaking it down
const shuffle = arr => { // Create a function that accepts one parameter
for (var i=0; i<arr.length-1; i++) { // create a for loop *
var x = i + genNum(arr.length-i)-1; // you create a variable 'x' that equal 'i' plus the random number -1 *
if (i != x) [arr[i], arr[x]] = [arr[x], arr[i]]; // check if 'i' doesn't equal 'x' - you then create two arrays?? I don't get it
}
};
Steven Parker
243,318 PointsThe use of "var" was unconscious, "let" is probably a better choice.
Here's how I would describe the code:
-
for (let i=0; i<arr.length-1; i++) {prepare to "shuffle" each item, one at a time
-
var x = i + genNum(arr.length-i)-1;randomly choose an item from the remaining ones not yet shuffled
-
if (i != x) [arr[i], arr[x]] = [arr[x], arr[i]];if we didn't pick the same one, swap the current one with the randomly chosen one
That last line contains a destructuring assignment, which allows two things to be swapped in one step. Otherwise you could do it using a temporary variable to hold one of the values as you juggle them.