JavaScript code to retrieve a random element from each element within an array containing both subarrays and strings

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.

Answer №1

To determine the type of value being processed, use the map callback in the following way:

return array.map(attr => Array.isArray(attr) ? getRandom(attr, 1) : attr);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Get a C-string from a local function that returns a C++ string value

Is the following code snippet guaranteed to work as intended, with no errors? #include <string> #include <iostream> using namespace std; string getString() { char s[] = "Hello world!"; return s; } int main() { cout << getSt ...

Using Javascript to extract information from the div element

Within my HTML code, I have a total of 4 <div> tags and a corresponding <a> tag for each of these <div> tags. Inside each div tag, there are 2 span tags and an additional a tag. Upon clicking the a tag, I aim to extract the product name ...

Error message stating that the callback function was not triggered by the injected JSONP script in Angular

Currently, I am running an application on localhost://3000 using npm server. Here is the content of my services file: import {Injectable} from "@angular/core"; import {Jsonp} from "@angular/http"; import 'rxjs/add/operator/map'; @Injectable() ...

Insert the user's choice as a MenuItem within the Select component

I currently have a default list of options for the user. However, I want to allow users to add their own category dynamically. This will trigger a dialog box to appear. How can I modify my code so that the value property starts from number 4? Take a look ...

Two-way binding does not function properly with custom directives on Internet Explorer version 9

Take a look at this unique angular application : <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script> <link href="style.css" rel="stylesheet" /> &l ...

Ways to properly format arrays and JSON data for display

After spending some time trying to resolve an issue on my own with no success, I am seeking assistance on how to properly display my encoded JSON data. Here is the code snippet that generates the JSON: //Defining messages $messages = array(); $message = a ...

What causes JSON.parse to overlook certain information?

When parsing a JSON response that contains HTML data from the endpoint http://registry.npmjs.org/core-js, I noticed an issue where the JSON.parse function does not fail but instead ignores the data I am trying to fetch. For example: fetch('http://re ...

Exploring Zustand through Laravel validation errorsUnderstanding Zustand can be

I'm currently working on incorporating Zustand into my NextJS application. I have set up a Laravel endpoint for user login functionality. When there are validation errors, the endpoint sends back JSON in the following format: { "message" ...

What is the process for generating Points with Three JS and React-Three-Fibre?

My current stack includes React, Three JS, and React-Three-Fibre I am aiming to generate an array of 100 Points with random colors, positions, and sizes. However, I find myself struggling with the process and would like to achieve this by predefining buff ...

Sorting function not working on dynamic Angular table

I'm currently facing a challenge with sorting a dynamic Angular table. If I manually code the table headers, everything works smoothly. Fiddle: https://jsfiddle.net/xgL15jnf/ <thead> <tr> <td> <a href="#" ...

Tips for marking a textarea as mandatory when a choice is made

I'm creating an .html document for conducting a complete system check and confirming various aspects of its functionality. In this page, there is a table within a form structure where each row represents a step in the system verification process (e.g. ...

Consistently encountering the message 'Error: timeout of 2000ms exceeded' while using Selenium

Good morning, Currently, I am in the process of learning how to use Selenium with JavaScript (specifically using Mocha). I have created a very basic test that is causing some issues during runtime. Whenever I run the test, a new instance of Chrome opens a ...

Leveraging React Native to position a view absolutely in the center of the screen without obstructing any other components

How can I center an image inside a view in the middle of the screen using position: "absolute"? The issue is that the view takes up 100% of the width and height of the screen, causing all components underneath it (such as input fields and buttons ...

Issue with integrating Shuffle.js search functionality with Bootstrap 4 cards

For the past few days, I've been experimenting with integrating Shuffle.js into my cards within Bootstrap 4. My goal is to achieve a visually pleasing shuffling effect when searching/filtering these cards. Below is the HTML structure and JavaScript c ...

Struggling with integrating API response formatting in React and updating state with the data

This is the content found in the file 'Search.js' import React, { Component } from 'react'; import * as BooksAPI from './BooksAPI' class Search extends Component{ constructor(props){ super(props); this.state={ ...

What is the significance of indexing a key within an embedded document?

I am still struggling to grasp the concept of how indexing a key of an embedded document truly functions. Let's say I have the following assortment of blog posts: { _id:0, author: 'John Doe', content: 'How does indexing ...

Is there a way to calculate the number of days between two dates that are stored in an array

I need assistance with extracting individual days from an array containing start and end dates. My goal is to store the days between the given dates in a new array. Array ( [0] => Array ( [start] => 2019-02-16 [end] => 2019-02 ...

Algorithm to compare strings in C++

What is your preferred algorithm for comparing strings? I personally use an O(n) solution: #include <string> bool stringCompare(char* str1, char* str2) { int length1 = strlen(str1), length2 = strlen(str2); if(length1 != length2) r ...

Keep the active button state when it is clicked in React JS within a functional component

When I click on a button, I want to remain in the section while also having the button stay in the background with a color that indicates my selection. This could be for breakfast, lunch, dinner, or any other section. const Categories = ({ categories, fi ...

What exactly happens when you use the increment operator with an array name?

Trying to understand how values move around with arrays, I found this code helpful. Everything is clear until the part that mentions ++mode[i][0] towards the end. I'm puzzled about what exactly this is incrementing. Just to clarify, this code isn&apos ...