JSFiddle - React, Tailwind, and code Playground

by Graham Fairweather

JavaScript

/*jslint maxerr: 50, indent: 4, browser: true, bitwise: true */
/*global console */

(function () {
    "use strict";

    function customRand(array, count) {
        var length = array.length,
            indexes = [],
            result = [],
            i = 0,
            rand,
            temp;

        while (i < length) {
            if (Object.prototype.hasOwnProperty.call(array, i)) {
                indexes.push(i);
            }

            i += 1;
        }

        i = 0;
        length = indexes.length;
        while (i < length) {
            rand = (Math.random() * i) | 0;
            temp = indexes[i];
            indexes[i] = indexes[rand];
            indexes[rand] = temp;
            i += 1;
        }

        indexes = indexes.slice(0, count).sort(function (a, b) {
            return a - b;
        });

        i = 0;
        length = indexes.length;
        while (i < length) {
            result[indexes[i]] = array[indexes[i]];
            i += 1;
        }

        return result;
    }

    var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20];

    console.log(customRand(arr, 5));
}());