How can I create every combination possible for the contents of two arrays?
A loop of this form
combos = [] //or combos = new Array(2);
for(var i = 0; i < array1.length; i++)
{
for(var j = 0; j < array2.length; j++)
{
//you would access the element of the array as array1[i] and array2[j]
//create and array with as many elements as the number of arrays you are to combine
//add them in
//you could have as many dimensions as you need
combos.push(array1[i] + array2[j])
}
}
How to create every combination possible between two array of objects?
Looks like you have the double looping part, but the object you are pushing into your array isn't what you say you expect. You are doing simple string concatenation.
origin[i].regionName + destination[j].regionName
Here is what I think is a more "react" way to loop over the data and return a result array. Reduce the origin
array into a new array, mapping in the combined object with the destination
array.
origin.reduce(
(result, origin) => [
...result,
...destination.map((destination) => ({
originreagion: origin.regionName,
destinationRegion: destination.regionName,
ts: "1606370160" // <-- set your real timestamp here
}))
],
[]
);
const origin = [
{
id: 1,
regionName: "Africa North"
},
{
id: 2,
regionName: "Africa West"
}
];
const destination = [
{
id: 5,
regionName: "Gulf"
},
{
id: 8,
regionName: "Middle East"
},
{
id: 9,
regionName: "Central America"
}
];
const result = origin.reduce(
(result, origin) => [
...result,
...destination.map((destination) => ({
originreagion: origin.regionName,
destinationRegion: destination.regionName,
ts: "1606370160"
}))
],
[]
);
console.log(result)
How do I generate combinations of two arrays?
You can iteratively generate all possible combinations of two arrays using streams
as follows:
String[] arr = {"E", "A", "C"};
String[] val = {"true", "false"};
// an array of possible combinations
String[] comb = Arrays.stream(arr)
.map(e -> Arrays.stream(val)
// append each substring
// with possible combinations
.map(v -> e + " " + v + " ")
// return Stream<String[]>
.toArray(String[]::new))
// reduce stream of arrays to a single array
// by sequentially multiplying array pairs
.reduce((arr1, arr2) -> Arrays.stream(arr1)
.flatMap(str1 -> Arrays.stream(arr2)
.map(str2 -> str1 + str2))
.toArray(String[]::new))
.orElse(null);
// output
Arrays.stream(comb).forEach(System.out::println);
E true A true C true
E true A true C false
E true A false C true
E true A false C false
E false A true C true
E false A true C false
E false A false C true
E false A false C false
See also: Generate all possible string combinations by replacing the hidden “#” number sign
Get all possible set of combinations of two arrays as an array of arrays with JavaScript
[[A, 1], [B, 2]]
is the same as
[[B, 2], [A, 1]]
in your case, which means that the solution depends on what you pair to the first elements of your array. You can pair n different elements as second elements to the first one, then n - 1 different elements as second elements to the second one and so on, so you have n! possibilities, which is the number of possible permutations.
So, if you change the order of the array elements but they are the same pair, they are equivalent, so you could view the first elements as a fixed ordered set of items and the second elements as the items to permutate.
Having arr1 = [a1, ..., an] and arr2 = [b1, ..., bn] we can avoid changing the order of a1. So, you permutate the inner elements and treat the outer elements' order as invariant, like:
const permutations = function*(elements) {
if (elements.length === 1) {
yield elements;
} else {
let [first, ...rest] = elements;
for (let perm of permutations(rest)) {
for (let i = 0; i < elements.length; i++) {
let start = perm.slice(0, i);
let rest = perm.slice(i);
yield [...start, first, ...rest];
}
}
}
}
var other = ['A', 'B', 'C'];
var myPermutations = permutations(['X', 'Y', 'Z']);
var done = false;
while (!done) {
var next = myPermutations.next();
if (!(done = next.done)) {
var output = [];
for (var i = 0; i < next.value.length; i++) output.push([other[i], next.value[i]]);
console.log(output);
}
}
how to generate all pairwise combinations between two arrays of unequal length in JavaScript?
Your code is fine. To get the structure similar to how you have it, you can enclose the values in an array.
let arr1 = ["tom", "sue", "jim"];let arr2 = ["usa", "japan"];
let pairs = [];for (var i = 0; i < arr1.length; i++) { for (var j = 0; j < arr2.length; j++) { pairs.push([arr1[i], arr2[j]]); }}console.log(pairs);
How to get all possible combinations from two arrays?
Use a triple loop:
for (int i=0; i < operators.length; ++i) {
for (int j=0; j < operators.length; ++j) {
for (int k=0; k < operators.length; ++k) {
System.out.println(numbers[0] + operators[i] + numbers[1] + operators[j] +
numbers[2] + operators[k] + numbers[3]);
}
}
}
You essentially want to take the cross product of the operators vector (if it were a vector). In Java, this translates to a triply-nested set of loops.
Creating all possible combinations from two arrays
from itertools import product
dicts = [{k:v for k,v in zip(keys, tup)} for tup in list(product(values, repeat=len(keys)))]
Related Topics
Chrome Extension - How to Get Http Response Body
How to Include Js File in Another Js File
Url Encode a String in Jquery for an Ajax Request
Testing Whether a Value Is Odd or Even
Why Is the Variable Holding the Input Value Always Logged as Empty
Save JSON String to Client Pc (Using HTML5 API)
How to Print a PDF from the Browser
What Tag in HTML Should I Use Without Special Meaning, Only to Carry Meta Data
How to Take a Snapshot of HTML5-Javascript-Based Video Player
What Is "Context" in Jquery Selector
Cryptic "Script Error." Reported in JavaScript in Chrome and Firefox
Check If Event Is Triggered by a Human
How to Check If Page Exists Using JavaScript
Difference Between Window.Location.Href=Window.Location.Href and Window.Location.Reload()
Avoid Window Jump to Top When Clicking #-Links
Uncaught Typeerror: Cannot Read Property 'Top' of Undefined
How to Use Any HTML5 Fanciness to Export Local Storage to Excel