
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
How to create every combination possible for the contents of two arrays in JavaScript
Suppose we have two arrays of literals like this −
const arr1 = ["A","B","C"]; const arr2 = ["1","2","3"];
We are required to write a JavaScript function that takes in two such arrays of literals. The function should then combine each element of the first array with each element of the second array and push them into a new array.
Therefore, the output for the above input should look like this −
const output = ["A1","A2","A3","B1","B2","B3","C1","C2","C3"];
Example
The code for this will be −
const arr1 = ["A","B","C"]; const arr2 = ["1","2","3"]; const prepareCartesian = (arr1 = [], arr2 = []) => { const res = []; for(let i = 0; i < arr1.length; i++){ for(let j = 0; j < arr2.length; j++){ res.push(arr1[i] + arr2[j]) } }; return res; }; console.log(prepareCartesian(arr1, arr2));
Output
And the output in the console will be −
[ 'A1', 'A2', 'A3', 'B1', 'B2', 'B3', 'C1', 'C2', 'C3' ]
- Related Articles
- How to Create an Array using Intersection of two Arrays in JavaScript?
- How to create arrays in JavaScript?
- How to find every element that exists in any of two given arrays once using JavaScript?
- Any possible combination to add up to target in JavaScript
- How to merge two arrays in JavaScript?
- How to join two arrays in JavaScript?
- How to multiply two Arrays in JavaScript?
- How to store the contents of arrays in a file using Java?
- Checking for the similarity of two 2-D arrays in JavaScript
- How to create the combination of rows in two data frames having same columns in R?
- How to get the difference between two arrays in JavaScript?
- JavaScript: create an array of JSON objects from linking two arrays
- isSubset of two arrays in JavaScript
- Finding the continuity of two arrays in JavaScript
- How to create combination of multiple vectors in R?

Advertisements