Generate a random sub-array from a larger array
By: Ajdin Imsirovic 11 January 2021
There are a few steps involved in this solution:
- we take an existing array,
- setup a new, blank array
- Run a for loop with 3 iterations
- On each iteration use
splice()
an array item at random usingMath.random()
- Push the existing members
- Flatten the new array
Let’s discuss how this works, in detail.
After practicing all these different ways of dealing with randomness in the past week:
- six-sided dice
- pick random array member
- return a true or false from a function at random
- get a random number from a range of numbers
- shuffle an array
- random password in JS
- add random CSS classes to a paragraph
…it shouldn’t be too hard to solve this exercise. Let’s start with an array:
Now let’s say we want to take three random items from the above array and store them in a new array.
1
2
3
4
5
6
7
8
9
10
11
(function() {
const fruits = ['apple','pear','mango','kiwi','lemon','plum'];
let newArr = [];
for (let i = 0; i < 3; i++) {
newArr.push(
fruits[Math.floor(Math.random() * fruits.length)]
)
}
console.log(newArr)
})()
However, this won’t work exactly as expected, since we can have duplicates in the resulting array, such as this:
The solution is to use a technique similar to shuffling an array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
(function() {
const fruits = ['apple','pear','mango','kiwi','lemon','plum'];
let newArr = [];
for (let i = 0; i < 3; i++) {
let item = fruits.splice(
Math.floor(
Math.random() * fruits.length), 1
);
newArr.push(item)
}
console.log(newArr)
})()
Now we’re getting an array of three arrays, each holding one member, for example:
Now, all we have to do is flatten the array:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
(function() {
const fruits = ['apple','pear','mango','kiwi','lemon','plum'];
let newArr = [];
for (let i = 0; i < 3; i++) {
let item = fruits.splice(
Math.floor(
Math.random() * fruits.length), 1
);
newArr.push(item)
}
newArr = newArr.flat();
console.log(newArr)
})()
Here’s the result of running the above code a few times:
Note:
This exercise comes from Book 3
of my book series on JS, available on Leanpub.com.