Take three elements at a time from array - javascript

I have an array composed by nine elements:
var ar = ['a','a','a','a','a','a','a','a','a'];
I need to control three elements at a time by a function that returns a true or false. If the first returns true, the others do not have to execute in order to obtain just one true result.
var one = fun(ar.slice(0, 3));
if (one != false) document.write(one);
var two = fun(ar.slice(3, 6));
if (two != false) document.write(two);
var three = fun(ar.slice(6, 9));
if (three != false) document.write(three);
How can I simplify this process? To avoid the creation of a multiarray.
Thanks !!

You could use an array with the slicing paramters and iterate with Array#some
function fun(array) {
return array.reduce(function (a, b) { return a + b; }) > 10;
}
var ar = [0, 1, 2, 3, 4, 5, 6, 7, 8];
[0, 3, 6].some(function (a) {
var result = fun(ar.slice(a, a + 3));
if (result) {
console.log(a, result);
return true;
}
});

Probably this is what you need.
Check out the demo below
var ar = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm'];
for(var i = 0; i < ar.length; i+=3){
console.log(ar.slice(i, i+3));
}

It sounds like some you want an iterator of sorts. An explicit example would be something like:
var input = [0, 1, 2, 3, 4, 5, 6, 7, 8];
// console.log(checkChunks(input, 2, checkChunkSum(10)));
console.log(checkChunks(input, 3, checkChunkSum(10)));
function checkChunks(arr, chunkLength, checker) {
var startIndex = 0;
var chunk;
while ((chunk = arr.slice(startIndex, startIndex += chunkLength)).length) {
var result = checker(chunk);
console.log('Checking chunk: ', chunk);
if (result !== false) {
return {
chunk: chunk,
result: result
};
}
}
return false;
}
function checkChunkSum(max) {
return function checkSum(arr) {
return arr.reduce(sum, 0) > max;
}
}
function sum(a, b) {
return a + b;
}

Related

Numerical arrays being loaded before those with letters

I have a quiz. Here is the array of questions. The program is supposed to loop through them in order. However, it is first going through all the arrays with numbers and then the ones with letters, as opposed to the order I put them in. Here are the questions:
allQuestions = {
'358670': ['358670', '967723', '214571', '569420', '630697', 0],
'mbdpf': ['ajcwh', 'xirgb', 'dzelv', 'mbdpf', 'xguqx', 3],
'637592': ['348335', '921186', '637592', '188551', '391500', 2],
'xhtjv': ['xhtjv', 'jneez', 'cthul', 'bulwl', 'kqfwc', 0],
'206471': ['206471', '419643', '366549', '871328', '926142', 0],
'mwdif': ['bzvai', 'kslgq', 'futgf', 'mwdif', 'sikyp', 3],
'980924': ['327151', '242777', '708582', '860616', '980924', 4],
'usiyi': ['iyfod', 'lapwg', 'dqmtt', 'dyvwk', 'usiyi', 4],
'768898': ['808547', '689143', '875754', '768898', '872606', 3],
'ziojg': ['xqdiv', 'cyqsu', 'akoed', 'obtpn', 'ziojg', 4]
};
Here's the codepen and here's the entire JS:
window.onload = function() {
var questionArea = document.getElementsByClassName('questions')[0],
answerArea = document.getElementsByClassName('answers')[0],
checker = document.getElementsByClassName('checker')[0],
current = 0,
allQuestions = {
'358670': ['358670', '967723', '214571', '569420', '630697', 0],
'mbdpf': ['ajcwh', 'xirgb', 'dzelv', 'mbdpf', 'xguqx', 3],
'637592': ['348335', '921186', '637592', '188551', '391500', 2],
'xhtjv': ['xhtjv', 'jneez', 'cthul', 'bulwl', 'kqfwc', 0],
'206471': ['206471', '419643', '366549', '871328', '926142', 0],
'mwdif': ['bzvai', 'kslgq', 'futgf', 'mwdif', 'sikyp', 3],
'980924': ['327151', '242777', '708582', '860616', '980924', 4],
'usiyi': ['iyfod', 'lapwg', 'dqmtt', 'dyvwk', 'usiyi', 4],
'768898': ['808547', '689143', '875754', '768898', '872606', 3],
'ziojg': ['xqdiv', 'cyqsu', 'akoed', 'obtpn', 'ziojg', 4]
};
function loadQuestion(curr) {
var question = Object.keys(allQuestions)[curr];
questionArea.innerHTML = '';
questionArea.innerHTML = question;
}
function loadAnswers(curr) {
var answers = allQuestions[Object.keys(allQuestions)[curr]];
answerArea.innerHTML = '';
for (var i = 0; i < answers.length -1; i += 1) {
var createDiv = document.createElement('div'),
text = document.createTextNode(answers[i]);
createDiv.appendChild(text);
createDiv.addEventListener("click", checkAnswer(i, answers));
answerArea.appendChild(createDiv);
}
}
function checkAnswer(i, arr) {
return function () {
var givenAnswer = i,
correctAnswer = arr[arr.length-1];
if (givenAnswer === correctAnswer) {
addChecker(true);
} else {
addChecker(false);
}
if (current < Object.keys(allQuestions).length -1) {
current += 1;
loadQuestion(current);
loadAnswers(current);
} else {
questionArea.innerHTML = 'Done!';
answerArea.innerHTML = '';
}
};
}
function addChecker(bool) {
var createDiv = document.createElement('div'),
txt = document.createTextNode(current + 1);
createDiv.appendChild(txt);
if (bool) {
createDiv.className += 'correct';
checker.appendChild(createDiv);
} else {
createDiv.className += 'false';
checker.appendChild(createDiv);
}
}
loadQuestion(current);
loadAnswers(current);
};
You're iterating over an object, and not over an array. The order of object keys is not fixed - Use an array if you need a specific order:
var obj = {
a: 'a',
1: 1,
x: 'x'
}
console.log('object keys', Object.keys(obj))
var arr = ['a', 1, 'x']
console.log('array values', arr)
Javascript objects provide no guarantees about the order of the elements. The order that you originally put the keys will not necessarily be the order that they are enumerated.
There are 2 main ways to approach this.
Create an array separate from the object with the keys in the correct order.
var keys = ['358670', 'mbdpf', '637592', 'xhtjv', '206471', 'mwdif', '980924', 'usiyi', '768898'];`
Use an array to store all of the data instead of an object.
allQuestions = [
{ key: '358670', data: ['358670', '967723', '214571', '569420', '630697', 0] },
{ key: 'mbdpf', data: ['ajcwh', 'xirgb', 'dzelv', 'mbdpf', 'xguqx', 3] },
// etc.
};
Objects in JavaScript, like dictionaries in most other languages, do not guarantee order! Arrays do.
Here's how you can wrap your data into an array:
allQuestions = [
{ 'name': '358670', 'contents': ['358670', '...'] },
{ 'name': 'mbdpf', 'contents': ['...'] }
];

segments of common values in sorted arrays

I would like to calculate the common segments in arrays that are already sorted:
Consider the following two arrays:
var arr1 = ['a','b','c','d'];
var arr2 = ['a','c','d'];
I would like to return ['a'],['b'],['c','d']
This is not the typical intersection, maintaining the order of the array values is crucial.
Is there a simple way to do this using underscore?
Presumably this works for you, at least with the given data.
var arr1 = ['a', 'b', 'c', 'd'],
arr2 = ['a', 'c', 'd'],
arr3 = [];
arr1.forEach(function (a, i) {
if (!i || this.next) {
arr3.push([a]);
if (a === arr2[this.index]) {
this.index++;
}
this.next = false;
return;
}
if (a < arr2[this.index]) {
arr3.push([a]);
this.next = true;
return;
}
if (a === arr2[this.index]) {
arr3[arr3.length - 1].push(a);
this.index++;
}
}, { index: 0, next: false });
document.write('<pre>' + JSON.stringify(arr3, 0, 4) + '</pre>');

Lodash swap adjacent items if condition is met

Say I have an array, [1, 2, 3, 4, 5, 3, 4, 6, 3, 7, 4]. I want to swap the values of 3 and 4 iff they are adjacent an in the order [3, 4] (i.e. [4, 3] remain intact). The result of the example would be [1, 2, 4, 3, 5, 4, 3, 6, 3, 7, 4].
Is there an elegant way to do this in Lodash without the use of for loops?
Edit:
How about
_.sortBy(arr, function(value, index) {
if (value === 3) {
return index + 0.75;
} else if (value === 4) {
return index - 0.75;
} else {
return index
}
});
Edit 2:
Went with the following (it's not actually 3 and 4).
return _.reduce(tags, function(out, tag) {
var word = tag[0];
if (out[0] && unitPowerSuffixes.hasOwnProperty(word)) {
out.splice(-1, 0, {
type: 'unit-power',
value: unitPowerSuffixes[word]
}); // Insert one from end
} else {
out.push(tag);
}
return out;
}, []);
Is there an elegant way to do this in Lodash without the use of for loops?
Yes, you can use reduce as follows:
var array = [1, 2, 3, 4, 5, 3, 4, 6, 3, 7, 4];
var result = _.reduce(array, swapAdjacentInOrder(3, 4), []);
alert(JSON.stringify(result));
function swapAdjacentInOrder(a, b) {
return function (result, element) {
var length = result.length;
if (length > 0 && element === b) {
var last = length - 1;
if (result[last] === a) {
result[last] = b;
element = a;
}
}
result[length] = element;
return result;
};
}
<script src="https://rawgit.com/lodash/lodash/master/lodash.min.js"></script>
However, the swapAdjacentInOrder function also has the following property:
var array = [3, 4, 4, 4];
var result = _.reduce(array, swapAdjacentInOrder(3, 4), []);
alert(JSON.stringify(result)); // [4, 4, 4, 3]
function swapAdjacentInOrder(a, b) {
return function (result, element) {
var length = result.length;
if (length > 0 && element === b) {
var last = length - 1;
if (result[last] === a) {
result[last] = b;
element = a;
}
}
result[length] = element;
return result;
};
}
<script src="https://rawgit.com/lodash/lodash/master/lodash.min.js"></script>
If you don't want that then you can do the following updated swapAdjacentInOrder function:
var array = [3, 4, 4, 4];
var result = _.reduce(array, swapAdjacentInOrder(3, 4), []);
alert(JSON.stringify(result)); // [4, 3, 4, 4]
function swapAdjacentInOrder(a, b) {
return function (result, element) {
var length = result.length;
if (length > 0 && element === b) {
var last = length - 1;
if (result[last] !== a || last > 0 && result[last - 1] === b);
else {
result[last] = b;
element = a;
}
}
result[length] = element;
return result;
};
}
<script src="https://rawgit.com/lodash/lodash/master/lodash.min.js"></script>
Hope that helps.
A really functional way would be to use something like splitOn. But we can do that using strings (not even needing lodash):
arr.join().split("3,4").join("4,3").split(",").map(Number)

How to search for multiple index(es) of same values in javascript array

I have a 1 dimensional array like:
var abc = ['a','a','b','a','c']
Now I want to get back all the indexes of 'a', that is 0, 1 and 3.
Are there any simple solutions?
P.S.
I know IndexOf or jQuery.inArray(). But they just returned the index of first matched element only
You could extend the basic Array Object with the following method:
Array.prototype.multiIndexOf = function (el) {
var idxs = [];
for (var i = this.length - 1; i >= 0; i--) {
if (this[i] === el) {
idxs.unshift(i);
}
}
return idxs;
};
Then the operation
var abc = ['a','a','b','a','c'];
abc.multiIndexOf('a');
would give you the result:
[0, 1, 3]
Jsperf comparison of unshift / push / push(reverse order)
You could use Array#reduce with Array#concat with a check for the wanted item, take the index or an empty array.
var abc = ['a', 'a', 'b', 'a', 'c'],
indices = abc.reduce((r, v, i) => r.concat(v === 'a' ? i : []), []);
console.log(indices);
ES5
var abc = ['a', 'a', 'b', 'a', 'c'],
indices = abc.reduce(function (r, v, i) {
return r.concat(v === 'a' ? i : []);
}, []);
console.log(indices);
Rather than using a for loop, you can use a while loop combined with indexOf:
var array = [1, 2, 3, 4, 2, 8, 5],
value = 2,
i = -1,
indizes = [];
while((i = array.indexOf(value, i + 1)) !== -1) {
indizes.push(i);
}
This will return you [1, 4] and of course could be combined with extending the prototype of Array.
The second argument of indexOf specifies where to start the search in the given array.
You can take advantage of the fact that $.map() does not push values in its resulting array when the function you pass returns undefined.
Therefore, you can write:
var abc = ["a", "a", "b", "a", "c"];
var indices = $.map(abc, function(element, index) {
if (element == "a") {
return index;
}
});
You also use reduce function on the array and push the indexes to accumulated array, you need start with an empty array, the good thing about reduce is it's async and also time execution is faster than for loop, also it's a native function on array, look at the below, hope it's helping:
var arr = [0, 1, 2, 3, 7, 2, 3, 4, 7, 8, 9, 2, 3];
function indexesOf(num) {
var reduced = arr.reduce(function(acc, val, ind, arr){
if(val === num){
acc.push(ind);
}
return acc;
}, []);
return reduced;
}
indexesOf(2); //[2, 5, 11]
AFAIK, there's no Javascript or jQuery function that does this in one step, you have to write a loop.
var indexes = [];
$.each(abc, function(i, val) {
if (val == "a") {
indexes.push(i);
}
}
Do it this way :
var abc = ['a','a','b','a','c'];
for (var i=0; i<abc.length; i++) {if(abc[i]=='a') {console.log(i)};}
If your array size is fixed, then you can find the first occurrence in the array using indexOf(). Use the found index value as starting point in indexOf() to find an other occurrence.
var firstOccurance = [your_array].indexOf(2)
var secondOccurance = [your_array].indexOf(2, firstOccurance + 1)
Demo
use for loop
var arr = ['a', 'a', 'b', 'a', 'c'];
var indexA = [];
for (var i = 0; i < arr.length; i++) {
if ("a" == arr[i]) indexA.push(i)
}
With ES6 syntax you could go with forEach and the ternary operator :
const abc = ['a','a','b','a','c']
let matchingIndexes = []
abc.forEach( (currentItem, index) => {
currentItem === 'a' ? matchingIndexes.push(index) : null
})
console.log(matchingIndexes) // [0, 1, 3]

Finding All Combinations (Cartesian product) of JavaScript array values

How can I produce all of the combinations of the values in N number of JavaScript arrays of variable lengths?
Let's say I have N number of JavaScript arrays, e.g.
var first = ['a', 'b', 'c', 'd'];
var second = ['e'];
var third = ['f', 'g', 'h', 'i', 'j'];
(Three arrays in this example, but its N number of arrays for the problem.)
And I want to output all the combinations of their values, to produce
aef
aeg
aeh
aei
aej
bef
beg
....
dej
EDIT: Here's the version I got working, using ffriend's accepted answer as the basis.
var allArrays = [['a', 'b'], ['c', 'z'], ['d', 'e', 'f']];
function allPossibleCases(arr) {
if (arr.length === 0) {
return [];
}
else if (arr.length ===1){
return arr[0];
}
else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var c in allCasesOfRest) {
for (var i = 0; i < arr[0].length; i++) {
result.push(arr[0][i] + allCasesOfRest[c]);
}
}
return result;
}
}
var results = allPossibleCases(allArrays);
//outputs ["acd", "bcd", "azd", "bzd", "ace", "bce", "aze", "bze", "acf", "bcf", "azf", "bzf"]
This is not permutations, see permutations definitions from Wikipedia.
But you can achieve this with recursion:
var allArrays = [
['a', 'b'],
['c'],
['d', 'e', 'f']
]
function allPossibleCases(arr) {
if (arr.length == 1) {
return arr[0];
} else {
var result = [];
var allCasesOfRest = allPossibleCases(arr.slice(1)); // recur with the rest of array
for (var i = 0; i < allCasesOfRest.length; i++) {
for (var j = 0; j < arr[0].length; j++) {
result.push(arr[0][j] + allCasesOfRest[i]);
}
}
return result;
}
}
console.log(allPossibleCases(allArrays))
You can also make it with loops, but it will be a bit tricky and will require implementing your own analogue of stack.
I suggest a simple recursive generator function as follows:
// Generate cartesian product of given iterables:
function* cartesian(head, ...tail) {
let remainder = tail.length ? cartesian(...tail) : [[]];
for (let r of remainder) for (let h of head) yield [h, ...r];
}
// Example:
const first = ['a', 'b', 'c', 'd'];
const second = ['e'];
const third = ['f', 'g', 'h', 'i', 'j'];
console.log(...cartesian(first, second, third));
You don't need recursion, or heavily nested loops, or even to generate/store the whole array of permutations in memory.
Since the number of permutations is the product of the lengths of each of the arrays (call this numPerms), you can create a function getPermutation(n) that returns a unique permutation between index 0 and numPerms - 1 by calculating the indices it needs to retrieve its characters from, based on n.
How is this done? If you think of creating permutations on arrays each containing: [0, 1, 2, ... 9] it's very simple... the 245th permutation (n=245) is "245", rather intuitively, or:
arrayHundreds[Math.floor(n / 100) % 10]
+ arrayTens[Math.floor(n / 10) % 10]
+ arrayOnes[Math.floor(n / 1) % 10]
The complication in your problem is that array sizes differ. We can work around this by replacing the n/100, n/10, etc... with other divisors. We can easily pre-calculate an array of divisors for this purpose. In the above example, the divisor of 100 was equal to arrayTens.length * arrayOnes.length. Therefore we can calculate the divisor for a given array to be the product of the lengths of the remaining arrays. The very last array always has a divisor of 1. Also, instead of modding by 10, we mod by the length of the current array.
Example code is below:
var allArrays = [first, second, third, ...];
// Pre-calculate divisors
var divisors = [];
for (var i = allArrays.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * allArrays[i + 1].length : 1;
}
function getPermutation(n) {
var result = "", curArray;
for (var i = 0; i < allArrays.length; i++) {
curArray = allArrays[i];
result += curArray[Math.floor(n / divisors[i]) % curArray.length];
}
return result;
}
Provided answers looks too difficult for me. So my solution is:
var allArrays = new Array(['a', 'b'], ['c', 'z'], ['d', 'e', 'f']);
function getPermutation(array, prefix) {
prefix = prefix || '';
if (!array.length) {
return prefix;
}
var result = array[0].reduce(function(result, value) {
return result.concat(getPermutation(array.slice(1), prefix + value));
}, []);
return result;
}
console.log(getPermutation(allArrays));
You could take a single line approach by generating a cartesian product.
result = items.reduce(
(a, b) => a.reduce(
(r, v) => r.concat(b.map(w => [].concat(v, w))),
[]
)
);
var items = [['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j']],
result = items.reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));
console.log(result.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Copy of le_m's Answer to take Array of Arrays directly:
function *combinations(arrOfArr) {
let [head, ...tail] = arrOfArr
let remainder = tail.length ? combinations(tail) : [[]];
for (let r of remainder) for (let h of head) yield [h, ...r];
}
Hope it saves someone's time.
You can use a typical backtracking:
function cartesianProductConcatenate(arr) {
var data = new Array(arr.length);
return (function* recursive(pos) {
if(pos === arr.length) yield data.join('');
else for(var i=0; i<arr[pos].length; ++i) {
data[pos] = arr[pos][i];
yield* recursive(pos+1);
}
})(0);
}
I used generator functions to avoid allocating all the results simultaneously, but if you want you can
[...cartesianProductConcatenate([['a', 'b'], ['c', 'z'], ['d', 'e', 'f']])];
// ["acd","ace","acf","azd","aze","azf","bcd","bce","bcf","bzd","bze","bzf"]
Easiest way to find the Combinations
const arr1= [ 'a', 'b', 'c', 'd' ];
const arr2= [ '1', '2', '3' ];
const arr3= [ 'x', 'y', ];
const all = [arr1, arr2, arr3];
const output = all.reduce((acc, cu) => {
let ret = [];
acc.map(obj => {
cu.map(obj_1 => {
ret.push(obj + '-' + obj_1)
});
});
return ret;
})
console.log(output);
If you're looking for a flow-compatible function that can handle two dimensional arrays with any item type, you can use the function below.
const getUniqueCombinations = <T>(items : Array<Array<T>>, prepend : Array<T> = []) : Array<Array<T>> => {
if(!items || items.length === 0) return [prepend];
let out = [];
for(let i = 0; i < items[0].length; i++){
out = [...out, ...getUniqueCombinations(items.slice(1), [...prepend, items[0][i]])];
}
return out;
}
A visualisation of the operation:
in:
[
[Obj1, Obj2, Obj3],
[Obj4, Obj5],
[Obj6, Obj7]
]
out:
[
[Obj1, Obj4, Obj6 ],
[Obj1, Obj4, Obj7 ],
[Obj1, Obj5, Obj6 ],
[Obj1, Obj5, Obj7 ],
[Obj2, Obj4, Obj6 ],
[Obj2, Obj4, Obj7 ],
[Obj2, Obj5, Obj6 ],
[Obj2, Obj5, Obj7 ],
[Obj3, Obj4, Obj6 ],
[Obj3, Obj4, Obj7 ],
[Obj3, Obj5, Obj6 ],
[Obj3, Obj5, Obj7 ]
]
You could create a 2D array and reduce it. Then use flatMap to create combinations of strings in the accumulator array and the current array being iterated and concatenate them.
const data = [ ['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j'] ]
const output = data.reduce((acc, cur) => acc.flatMap(c => cur.map(n => c + n)) )
console.log(output)
2021 version of David Tang's great answer
Also inspired with Neil Mountford's answer
const getAllCombinations = (arraysToCombine) => {
const divisors = [];
let permsCount = 1;
for (let i = arraysToCombine.length - 1; i >= 0; i--) {
divisors[i] = divisors[i + 1] ? divisors[i + 1] * arraysToCombine[i + 1].length : 1;
permsCount *= (arraysToCombine[i].length || 1);
}
const getCombination = (n, arrays, divisors) => arrays.reduce((acc, arr, i) => {
acc.push(arr[Math.floor(n / divisors[i]) % arr.length]);
return acc;
}, []);
const combinations = [];
for (let i = 0; i < permsCount; i++) {
combinations.push(getCombination(i, arraysToCombine, divisors));
}
return combinations;
};
console.log(getAllCombinations([['a', 'b'], ['c', 'z'], ['d', 'e', 'f']]));
Benchmarks: https://jsbench.me/gdkmxhm36d/1
Here's a version adapted from the above couple of answers, that produces the results in the order specified in the OP, and returns strings instead of arrays:
function *cartesianProduct(...arrays) {
if (!arrays.length) yield [];
else {
const [tail, ...head] = arrays.reverse();
const beginning = cartesianProduct(...head.reverse());
for (let b of beginning) for (let t of tail) yield b + t;
}
}
const first = ['a', 'b', 'c', 'd'];
const second = ['e'];
const third = ['f', 'g', 'h', 'i', 'j'];
console.log([...cartesianProduct(first, second, third)])
You could use this function too:
const result = (arrayOfArrays) => arrayOfArrays.reduce((t, i) => { let ac = []; for (const ti of t) { for (const ii of i) { ac.push(ti + '/' + ii) } } return ac })
result([['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j']])
// which will output [ 'a/e/f', 'a/e/g', 'a/e/h','a/e/i','a/e/j','b/e/f','b/e/g','b/e/h','b/e/i','b/e/j','c/e/f','c/e/g','c/e/h','c/e/i','c/e/j','d/e/f','d/e/g','d/e/h','d/e/i','d/e/j']
Of course you can remove the + '/' in ac.push(ti + '/' + ii) to eliminate the slash from the final result. And you can replace those for (... of ...) with forEach functions (plus respective semicolon before return ac), whatever of those you are more comfortable with.
An array approach without recursion:
const combinations = [['1', '2', '3'], ['4', '5', '6'], ['7', '8']];
let outputCombinations = combinations[0]
combinations.slice(1).forEach(row => {
outputCombinations = outputCombinations.reduce((acc, existing) =>
acc.concat(row.map(item => existing + item))
, []);
});
console.log(outputCombinations);
let arr1 = [`a`, `b`, `c`];
let arr2 = [`p`, `q`, `r`];
let arr3 = [`x`, `y`, `z`];
let result = [];
arr1.forEach(e1 => {
arr2.forEach(e2 => {
arr3.forEach(e3 => {
result[result.length] = e1 + e2 + e3;
});
});
});
console.log(result);
/*
output:
[
'apx', 'apy', 'apz', 'aqx',
'aqy', 'aqz', 'arx', 'ary',
'arz', 'bpx', 'bpy', 'bpz',
'bqx', 'bqy', 'bqz', 'brx',
'bry', 'brz', 'cpx', 'cpy',
'cpz', 'cqx', 'cqy', 'cqz',
'crx', 'cry', 'crz'
]
*/
A solution without recursion, which also includes a function to retrieve a single combination by its id:
function getCombination(data, i) {
return data.map(group => {
let choice = group[i % group.length]
i = (i / group.length) | 0;
return choice;
});
}
function* combinations(data) {
let count = data.reduce((sum, {length}) => sum * length, 1);
for (let i = 0; i < count; i++) {
yield getCombination(data, i);
}
}
let data = [['a', 'b', 'c', 'd'], ['e'], ['f', 'g', 'h', 'i', 'j']];
for (let combination of combinations(data)) {
console.log(...combination);
}

Categories