I have an array that contains both strings and arrays. My goal is to create a function where I can pass this array and get back a randomly selected value from each nested array, while retaining the full string when the element is a string. Currently, my solution works for arrays within the array but only returns a random character instead of the entire string when the element is a string.
Below is an example showcasing my function and the issue with simulated data:
Although my method functions properly when each nested array has more than one element, it only picks one random letter from the single-element arrays.
// Function to sample K elements from an array without replacement
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;
};
// Define a function that randomly selects one element from each subarray
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 the function
get1RandomForEach(one_element) // Returns 1 char
get1RandomForEach(multiple_elements) // Returns 1 char for each element
get1RandomForEach(array_of_arrays) // Desired output achieved!
get1RandomForEach(array_of_mixed) // Returns 1 char for the 3rd element
Is there a way to use map to convert each element into an array? I am concerned about creating additional nested arrays within the main array. It's worth noting that this situation differs from previous inquiries as I do not have an array of arrays in this case.