jeudi 25 octobre 2018

Getting n random elements from array and creating duplicates when there's not enough elements

I have arrays of objects, ex:

let array1 = [
{name: '1', image: '1.jpg'},
{name: '2', image: '2.jpg'},
{name: '3', image: '4.jpg'},
{name: '4', image: '5.jpg'},
];

I want to get n random element of it and found function that serves this purpose:

function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);

        var x = Math.floor(Math.random() * len);
        result[n] = arr[x in taken ? taken[x] : x];
        taken[x] = --len in taken ? taken[len] : len;
    }
return result
}

The only problem is that when I want to have n > arr.length this does not work. I'd like to figure out how to increase number of elements in this case. For example repeating elements that are already in it.

I tried adding conditional:

if(n > len) {
    arr.push(arr);
    console.log(arr);
}

But it does me no good since, the elements are pushed as an another object, and not separately, check the console.log:

0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: Array(5)
0: {name: "1", image: "1.jpg"}
1: {name: "2", image: "2.jpg"}
2: {name: "3", image: "4.jpg"}
3: {name: "4", image: "5.jpg"}
4: (5) [{…}, {…}, {…}, {…}, Array(5)]
length: 5

None of other things I tried doesn't work. If someone could figure out the way around it I would really appreciate it.




Aucun commentaire:

Enregistrer un commentaire