Generate a random sub-array from a larger array

By: Ajdin Imsirovic 11 January 2021

There are a few steps involved in this solution:

  1. we take an existing array,
  2. setup a new, blank array
  3. Run a for loop with 3 iterations
  4. On each iteration use splice() an array item at random using Math.random()
  5. Push the existing members
  6. Flatten the new array

Let’s discuss how this works, in detail.

Woman holding polished stones

After practicing all these different ways of dealing with randomness in the past week:

…it shouldn’t be too hard to solve this exercise. Let’s start with an array:

const fruits = ['apple','pear','mango','kiwi','lemon','plum'];

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:

(3) ["plum", "plum", "apple"]

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:

(3) [Array(1), Array(1), Array(1)]
0: ["pear"]
1: ["kiwi"]
2: ["lemon"]

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:

(3) ["plum", "lemon", "mango"]
(3) ["kiwi", "pear", "lemon"]
(3) ["plum", "pear", "kiwi"]



Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.



Feel free to check out my work here: