Combine all possible pairings of elements from two distinct arrays

Is there a way to combine the elements of two arrays and return them in a new array? Let's say we have these two arrays:

const whoArr = ["my", "your"];    
const credentialArr = ["name", "age", "gender"].   

The desired outcome is a new array with the elements:

["my name", "my age", "my gender", "your name", "your age", "your gender"]

Neither .join nor .concat seem to solve this problem.

Answer №1

To iterate over array 1 and array 2, you can implement nested loops.

Instead of using forEach(), you have the option to utilize a standard for loop or a for of loop:

const whoArr = ["my", "your"];
const credentialArr = ["name", "age", "gender"];

const output = [];
whoArr.forEach(who => {
  credentialArr.forEach(cred => {
    output.push(who + ' ' + cred)
  })
})

console.log(output)

Alternatively, you can achieve the same outcome by employing for of loops and template literals for creating the string:

const whoArr = ["my", "your"];
const credentialArr = ["name", "age", "gender"];

const output = [];
for (let who of whoArr) {
  for (let cred of credentialArr) {
    output.push(`${who} ${cred}`);
  }
}

console.log(output)

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

Performing numerous asynchronous MongoDB queries in Node.js

Is there a better way to write multiple queries in succession? For example: Space.findOne({ _id: id }, function(err, space) { User.findOne({ user_id: userid }, function(err, user) { res.json({ space: space, user: user}); }); }); It can g ...

Using nodeJS's util module to format and pass an array

I've been using util.format to format strings like this: util.format('My name is %s %s', ['John', 'Smith']); However, the second parameter being an array ['John', 'Smith'] is causing issues because m ...

Understanding the mechanism behind how the import statement knows to navigate to the package.json file

I find myself stuck in bed at the moment, and despite numerous Google searches with no clear answers, I have chosen to seek help here. Could someone please clarify how scoping works when using import in TypeScript and determining whether to check the pack ...

Trouble locating DOM element in Angular's ngAfterViewInit()

Currently, I am attempting to target a specific menu item element within my navigation that has an active class applied to it. This is in order to implement some customized animations. export class NavComponent implements AfterViewInit { @ViewChild(&a ...

JavaScript function not being executed after AJAX response in HTML

There seems to be a problem with my jQuery code. After receiving an html response from an ajax call and prepending it to a div, a div within that received html is not triggering a function in my external javascript file. In the index.php file, I have incl ...

Issues with Angular application navigation in live environment

While my website functions perfectly on the development server, I encounter a strange error when I publish it to production on GitHub pages. Visiting the URL (yanshuf0.github.io/portfolio) displays the page without any issues. However, if I try to access y ...

Locate the parent element using a unique child element, then interact with a different child element

Can you help me come up with the correct xpath selector for this specific element? The element only has a unique href. Is it possible to locate the element by searching for the text iphone X within the href="#">iphone X and also checking for its paren ...

Guide to transforming Excel formulas into JavaScript

In my Excel sheet, I have the following formula: =IF($F6=0,"",IF(I6=0,"",$F6/I6)) where F6=7000 and I6 is empty. The Excel result is displaying no data for the formula. Now, I need to convert this formula into JavaScript. function AB6(F6) { var ...

Struggling to navigate web pages with Selenium using Java is proving to be a challenge

I am currently working on using Selenium's HtmlUnitDriver and WebElement classes in Java to automate clicking the "Download as CSV" button on Google Trends. The issue that I am encountering is that the button remains hidden until another settings men ...

Guide on excluding a specific element using an Xpath expression

I am seeking a solution to craft an XPath expression that can target all <p> elements except for p[6] and p[7]. Currently, I have formulated this expression: //div[@class="Job-Description app-responsive-jd"]/p[1], which is functioning corre ...

What steps should I take to resolve the textarea border bottom CSS effect?

My simple border bottom animation is working fine with a basic input element, but it's not functioning properly when used with a textarea. (If using JavaScript is necessary for a solution, please provide guidance) How can I adjust the height of a te ...

Conceal a secret input element's value upon clicking a submit button (using PHP and jQuery)

Greetings, I'm facing an issue and need your assistance: Here's the scenario - I have a form that gathers First Name, Last Name, and City from the user. Upon clicking submit, the provided information is then showcased within a table as follows: ...

Retrieve particular JSON information on a single webpage by selecting an element on a separate page

My goal is to fetch specific information from a JSON file and display it on different HTML pages by clicking a button. I will achieve this using jQuery and plain JS. For the first HTML page, I want to show all products from the JSON in an element with id= ...

What is the best way to utilize JSONP to display an entire HTML code with an alert?

When I attempt to use cross-domain ajax to retrieve the entire HTML page code, I keep receiving a failed message. The console log shows: "Uncaught SyntaxError: Unexpected token <" Below is my AJAX function: function fetchData(){ var url = documen ...

Working with Matrices in Python

Currently, I am working on creating a function that takes a Matrix, row number, and column number as input. The goal is to modify the matrix so that it contains a 1 in the specified A(i,j) position and zeros elsewhere in the i-th column using only row oper ...

Deliver integers using Express.js

When I try to send a response with Express using the code below, it doesn't work: res.send(13245) An error message is displayed: express deprecated res.send(status): Use res.sendStatus(status) instead src/x.js:38:9 (node:25549) UnhandledPromise ...

javascript download multiple PDF files on Internet Explorer

I am facing an issue with downloading multiple PDF files In my list, I have various a elements with links to different PDF files. I created a loop to go through each a element and generate an iframe using the value of the href as the source. This solutio ...

Performing a double running of an Express GET request with an :id parameter

I'm working on an API using node and express, where the main aim is to capture the :id parameter from the request and store it in a variable. This will allow me to query a specific table in my SQLite database based on that particular id. However, I am ...

The function called Nuxt: n2 is not defined

When using Nuxt 3, I encountered a TypeError that looks like the following: Uncaught TypeError: n2 is not a function My issue revolves around a button that triggers the function toggleSelectRow with a @click.prevent directive. The function in question is ...

Display additional information from a JSON file after choosing an ID with AngularJS Select

After saving a JSON file filled with information, I managed to successfully populate a select menu with the names of each element from the JSON data using this code snippet: <select ng-model="car.marca" ng-options="item.brakeId as item.name for item in ...