Shuffle array elements in JavaScript

I need help with manipulating an array containing nested arrays. Here's an example:

const arr = [[red,green],[house,roof,wall]]

Is there a method to combine the nested arrays so that the output is formatted like this?

red house, red roof, red wall, green house, green roof, green wall

Answer №1

Kindly review the code snippet below:

const arr = [['red','green'],['house','roof','wall']];
const array1 = arr[0];
const array2 = arr[1];
const new_arr = [];
for(let i=0; i< array1.length; i++){
    for(let j=0; j< array2.length; j++){
        new_arr.push(array1[i] + ' ' +array2[j]);
    }
}
console.log(new_arr); 
// output ['red house', 'red roof', 'red wall', 'green house', 'green roof', 'green wall']
console.log(new_arr.join(',')); 
// output: red house, red roof, red wall, green house, green roof, green wall

Answer №2

Utilizing a nested map() function along with 2 join() methods to convert it into a string

const arr = [ [ 'red', 'green' ],['house','roof','wall']];

const res = arr[0].map(a => arr[1].map(b => `${a} ${b}`).join(', ')).join(', ');

console.log(res);

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

Dynamically obtaining the content of a tag using jQuery

Although this question may have been asked multiple times before, I am encountering a peculiar issue. Let me explain the scenario: Within this tag, there is a dynamically loaded integer: <i id="my_id">{{integer value}}</i> I am attempting t ...

How can I connect the Bootstrap-datepicker element with the ng-model in AngularJS?

Below is the html code for the date field : <div class='form-group'> <label>Check out</label> <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" plac ...

How to add 1 to the final element in a JavaScript

I'm currently working on a task that involves incrementing the last element in an array using pop() and push(). However, I'm facing an issue where the original values are being retained after I try to increment the popped array. The objective is ...

I require a way to decelerate the speed of the roulette wheel's rotation

For my assignment, I'm tasked with creating a roulette spin wheel code in JavaScript without using any plugins. I need to incorporate some conditions before executing the code, particularly for slowing down the speed of the roulette spin. Additionally ...

transmitting error messages from a service to a controller in AngularJS

Controller.js var vm = this; vm.admin = {}; vm.add = function () { API.addAdmin(token, vm.admin) .then(function (resp) { vm.hideForm = true; vm.showButton = true; Notify.green(resp); }, function (re ...

Replacing variables in a function: A step-by-step guide

I have frequently used the replace function to eliminate classes in JavaScript. Currently, I am working on creating a JavaScript function that allows me to remove a specific class from an element by passing in the element and the class name. changeAddress ...

Sending information from a rails controller to a react component

Wondering how to pass the example @post = Post.all from the controller to React component props while integrating Rails with React via Webpacker. Is it necessary to do this through an API or is there another way? ...

tips for revealing content in a div by sliding from right to left

I came across a fiddle that animates from bottom to top when the cursor hovers over it. Is there a way to modify it so that it animates from right to left on click, and then hides the content? After hiding the content, I would like to have a button that a ...

Concealing scroll bars while still maintaining the ability to scroll by using overflow:scroll

Similar Question: How to hide the scrollbar while still allowing scrolling with mouse and keyboard I have created a sidebar for a web application that needs to enable users to scroll through it without displaying a scrollbar. The content is 500px high ...

Detecting a targeted POST event in JavaScript without any libraries

In a situation I'm facing, an AngularJS website is not loading jQuery (except for jQLite). My goal is to monitor events with particular parameters. Unfortunately, I'm unable to make any changes to the source code. However, by examining the event ...

I'm wondering why this isn't working properly and not displaying the closing form tag

What could be the reason for this not functioning properly? The tag appears to close on its own and the closed tag is not being displayed. As a result, the if(isset($_POST['payoneer-btn'])) statement is not triggering. https://i.stack.imgur.com/ ...

Assortment of versatile containers

When working with a map of Entry objects and having an array in a class, I wondered if it was necessary to use a typecast as my instructor suggested. Here is the code snippet: private Entry<K,V> array; After initializing the array with: array = ne ...

Utilizing jQuery.post to generate a dynamic dropdown menu

I recently designed a dropdown list that functions well on a standalone page. However, I encountered an issue when attempting to display it in a table on another page using jQuery.post(). The contents appear to overflow from the dropdown list. The jQuery ...

Verify whether the input field contains a value in order to change certain classes

My meteor-app includes an input field that dynamically changes position based on whether it contains content or not. When a user begins typing, with at least one character, the input field moves to the top of the page. In my current approach, I am using a ...

Utilize React Redux to send state as properties to a component

When my React Redux application's main page is loaded, I aim to retrieve data from an API and present it to the user. The data is fetched through an action which updates the state. However, I am unable to see the state as a prop of the component. It s ...

Exploring Objects using the for-in loop in ReactJS

This code is written in Reactjs. I am attempting to iterate through and print object data, but I keep encountering an error --> TypeError: Cannot read properties of undefined (reading 'state'). Could someone please help me identify what I am d ...

Is there a way to adjust the height pixel value in my code so it can be dynamic?

I have created a simple script that allows selected objects to fade in as the user scrolls down. However, my issue is that this script is quite rigid. If I were to apply it to 20 different objects, for example, I would need to manually adjust the height ea ...

What is the best way to stop a series of Ajax promises from continuing?

Managing multiple ajax requests that are dependent on each other can be tricky, especially when you need to stop the chain if one of the requests returns false. Check out this sample code snippet below: // Implementing a promise chain return this.getBan ...

Is there a way to prevent the Alt+F4 function from closing tabs in the Internet Explorer browser

Ctrl+W and Alt+F4 can be used to close the IE browser, but I am looking to disable this default action. While I have found a way to handle the Ctrl+W command, I am struggling with disabling the Alt+F4 event. It seems that other Alt+Key events like Alt+En ...

Setting the default value in a Reactive form on the fly: A step-by-step guide

When creating a table using looping, I need to set the default value of my Reactive Form to `Repeat` if the loop value matches a particular character, otherwise I want it to be empty. Here is my code: typescript rDefault:string = ""; create(){ ...