Try utilizing the Array.map method with a two-dimensional array

My current challenge involves a 2-dimensional Array where I am attempting to implement a "randomBool" function on each of the elements within it.

The "randomBool" function essentially generates a random boolean value:

const randomBool = () => Boolean(Math.round(Math.random()));

Here is the 2-dimensional Array that I am working with:

var test = [
    ["just","some","random","text"],
    [1412,"test",1278391]
]

I have structured a nested for-loop as follows:

for (let el of test){
    for(let i in el){
        el[i] = randomBool();
    }
}

I initially attempted this solution using map but encountered an issue:

test.forEach(el => el.map(el2 => randomBool()));

However, this approach was unsuccessful. Can anyone provide insights into why it didn't work?

Answer №1

To achieve the desired outcome, you must utilize two nested mappings.

const randomBools = test.map(outer => outer.map(inner => randomBool()))

The forEach method is typically used to iterate over each item in a sequence to execute some form of side effect without returning anything or altering the initial array. For instance, displaying each item on the console.

Conversely, map is designed to take an array as input and generate a new array of equal length, with the values modified in some manner, while leaving the original array unchanged. For example, converting all words in a list to uppercase.

To transform data in your existing 2D array and produce a new 2D array, you should nest your map functions. This approach will first map over the rows (outer), followed by the columns (inner). The outcomes of the inner mappings will be accumulated within the outer mapping, resulting in a 2D array containing the updated values, all accomplished without modifying the original array.

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

Delay with Vue.js v-bind causing form submission to occur before the value is updated

Trying to update a hidden input with a value from a SweetAlert modal, but encountering issues. The following code isn't working as expected - the form submits, but the hidden field's value remains null. HTML: <input type="hidden" name="inpu ...

Issue with Electron-vue: 'compute:' not functioning as expected

My attempt to create a simple example using the element-ui library was not successful. There are two 'switches' with different active state values: 2 and 1. The values of the switches are supposed to be displayed in <p>{{sw1}}</p> and ...

Sorting or filtering with two elements in the option value in AngularJS

I have been struggling for a while now to find a solution to this issue. How can I display the query for the third option value, which should show the filter of DB || CSLB from a json file? <select ng-model="search.source"> <option value="DB"& ...

The data sent within an event does not trigger reactivity

Not producing errors, just failing to function. The addition of this also has no impact. input( type="number" v-model="myData" @wheel="wheelIt($event, myData, myMethod)" ) ... methods: { wheelIt ( event, data, func ) { if ( event.deltaY ...

Submitting requests in Node.js Express

Can a request for a specific route be dropped using Node.js and express? For example, not returning an HTTP status or any headers, but simply closing the connection? app.get('/drop', function(req, res) { //What is the method to drop the requ ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

Query MySQL and automatically populate form fields with the data retrieved after the user triggers an "onexit" or "onsubmit" event, all without having to reload the page,

Seeking a way to auto-fill form fields with data from MySQL database. The goal is to input a value in a text field, search the database matching that value, and populate the remaining form fields without having to navigate away from the page. If anyone h ...

In my app.post request in node.js and express, the body object is nowhere to be found

Having an issue with node.js and express, trying to fetch data from a post request originating from an HTML file. However, when I log the request, the req.body object appears empty. I've added a console.log(req.body) at the beginning of my app.post(" ...

Instructions for passing a JavaScript variable to a PHP MySQL database

I am attempting to integrate a JavaScript variable into PHP MySQL, but I'm encountering issues with the insertion. Currently, it is being inserted as <javascript>document.write(window.outerWidth); </javascript> x <javascript>document ...

How can I retrieve the value of an HTML component when submitting a form?

In my ExpressJS application, I have two pages: home and user. In the home.js file, I create a form that navigates to the user.js page when submitted. While I am able to retrieve values from input components, I am facing issues with other components. How ca ...

Utilizing the JavaScript map method to structure API response data

Here is the JSON data I have: { "result": [{ "name": "a", "value": 20, "max": 100, "sale_value": [{ "no": 1, "name": "aaaaa", "price": 200 }, { "no": 2, ...

The functions that have been imported are not defined

I encountered a Error in created hook: "TypeError: _api__WEBPACK_IMPORTED_MODULE_0__.default.$_playerApi_getPlayers is not a function" issue while using Webpack through Vue CLI on my webpage. Below is the structure of my project directory: . + main.js + ...

AngularJS ng-map defines the view position using rectangular coordinates

Is there a way to set the position of ng-map view using the ng-map directive not as the center value of [40.74, -74.18], but instead as a rectangle defined by the corner values of the map view (north, south, east, west)? Currently, I have this code: < ...

Loss of data in the local storage when the page is reloaded

click here to see image I have managed to save data to local Storage successfully, but it keeps disappearing when I reload the page. Can someone guide me on how to handle this issue? I am new to this and would greatly appreciate any help. Thank you. https ...

Unable to use href attribute as intended

HTML: <a id="Switch">Click here to switch</a> <a href="image1_large.png" class="mainA blade"> <img id="mainImage" src="image1.png"/></a> Javascript: <script> $(function() { $('#Switch').click(functio ...

Tips for displaying animations only the first time using HTML and CSS:

Upon the initial visit to my website, a captivating animation introduces itself with the words "Hello. I'm Bob" as it gracefully fades into view. Navigating through the menu bar allows users to explore different sections of the site. However, there ...

Vue.js - Displaying validation errors when a user interacts outside of a component

The ExamEditor Vue component I am working on is quite complex, consisting of sub-components like QuestionEditor and ExerciseEditor. These components are all tied to an exam object that contains nested arrays with questions and more. The layout inside the e ...

Position items within the dynamically generated div without appending them

Utilizing JavaScript, I dynamically generate a line but struggle to position two balls at both the 1/3 mark from the beginning and end. For reference, please view the image below. I aim to have two balls appear upon pressing enter in the input box. Despite ...

Using jQuery or JavaScript to clear multiple selections in a multiselect dropdown when a button is clicked

Is there a way to clear the dropdown selections once my function saves data to local storage? You can refer to this fiddle for more details: http://jsfiddle.net/3u7Xj/139/ I already have code in place to handle other form elements: var $form = $("#formI ...

How to Avoid Duplicating Documents in MongoDB?

I'm currently exploring effective methods to avoid saving duplicate documents in MongoDB. Currently, my form captures the user's URL input. The workflow is as follows: Validate if the user's URL is valid (using dns.lookup). If the use ...