Home:ALL Converter>Javascript: returning random element from each element in an array of arrays *and strings*

Javascript: returning random element from each element in an array of arrays *and strings*

Ask Time:2020-05-13T05:17:54         Author:socialscientist

Json Formatter

I am have an array containing strings and arrays. I am trying to create a function where I pass this array and return a randomly selected value from each array within the array and the full string others. Unfortunately, my current solution works when every element of the array is itself an array, but only returns a random character from the string when the element is a string. I'd like to return the full string.

Here's a working example with my function and showing the issue with fake data:

While my solution works when each array contains more than 1 element, my approach chooses 1 random letter from the 1 element when an array contains only 1 element.

// We'll first, define a function to sample K elements from an array // without replacement. This wil be useful for random assignment.

// Define a function to N random elements from an array
function getRandom(arr, n) {
    var result = new Array(n),
        len = arr.length,
        taken = new Array(len);
    if (n > len)
        throw new RangeError("getRandom: more elements taken than available");
    while (n--) {
        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;
};

// Create a function that, given an array X containing
// arrays 1,2,3...k, randomly select one element from each 1, 2, 3, ...k
// and return an array containing the values
    function get1RandomForEach(array){
        return array.map(attr => getRandom(attr, 1));
    }

// Generate fake data 
   var one_element = ["foobar"];
   var multiple_elements =  ["foo", "bar"];
   var array_of_arrays = [["foo","bar"], ["foo", "bar"], ["foo"]];
   var array_of_mixed = [["foo","bar"], ["foo", "bar"], "foo"]];


// Apply function
  get1RandomForEach(one_element) // 1 char
  get1RandomForEach(multiple_elements) // 1 char for each element
  get1RandomForEach(array_of_arrays) // this is what I want!
  get1RandomForEach(array_of_mixed) // 1 char for 3rd element

Is this as simple as somehow using map to convert each element of the array into an array? But then I am worried I would create another set of arrays within the array. Note that this is different previous posts because I do not have an array of arrays (which is one of the example cases showing what I want).

Author:socialscientist,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/61762126/javascript-returning-random-element-from-each-element-in-an-array-of-arrays-an
yy