Assuming I have an array like this: [A, B, C, D, E, F]
, How can I group them like this:
[[A, B], [B, C], [C, D], [D, E], [E, F]]
(Notice how every last element is shared with the next group, but with the opposite index.)
I know this ain't a big deal of a problem, but I'm trying to keep it simple and short, maybe with Array.reduce() if possible:
arr.reduce(function (rows, key, index) {
return (index % 2 == 0 ? rows.push([key])
: rows[rows.length-1].push(key)) && rows;
}, []);
// Output: [[A, B], [C, D], [E, F]]
One liner solution is
arr.map((c, i) => [c, arr[i + 1]]).slice(0, -1)
SOLUTION 1
You can use map and filter here to achieve the result
At current index return an array which will contain current element and next element till last element
const arr = ['A', 'B', 'C', 'D', 'E', 'F'];
const result = arr
.map((c, i) => (i < arr.length - 1 ? [c, arr[i + 1]] : null))
.filter(Boolean);
console.log(result);
SOLUTION 2
You can also acheve this if you get all array combination and remove last one as:
const arr = ['A', 'B', 'C', 'D', 'E', 'F'];
const result = arr.map((c, i) => [c, arr[i + 1]]).slice(0, -1);
console.log(result);
Just with reduce method, you can add the current item and the item after it in an array, and then push this array into the accumulator of the reducer method, and before push you need to check if the current item isn't last item in the array.
const arr = ['A', 'B', 'C', 'D', 'E', 'F']
const result = arr.reduce((acc, item, index) => {
const nextItem = arr[index + 1]
nextItem ?? acc.push([item, nextItem])
return acc
}, [])
console.log(result)
If you don't want to stick to the reduce() approach here's another method using map() and slice().
const data = ['A', 'B', 'C', 'D', 'E', 'F'];
const result = data.map((_, i) => (i < data.length - 1 ? data.slice(i, i + 2) : null)).filter(Boolean);
console.log(result);
The simplest will be a standard for loop. It happens to also be shorter than many of the reduce() answers with no extraneous filters or conditions.
const arr = ['A', 'B', 'C', 'D', 'E', 'F'];
const result = [];
for (let i = 0; i < arr.length - 1; i++) {
result.push([arr[i], arr[i + 1]]);
}
console.log(result);
Alternatively a while loop is actually shorter if a little less transparent.
const arr = ['A', 'B', 'C', 'D', 'E', 'F'];
let result = [], i = 0;
while (i < arr.length - 1) {
result.push([arr[i], arr[++i]]);
}
console.log(result);
I've got array of variables and next variable which I want to add alphabetically. It goes A-Z and after that AA, AB, AC etc..
so in when next variable is E I want to add it at the end of letters with length=1, if next variable would be AC I'd add it at the end on letters with length=2 etc. I tried to do it with findIndex, but it returns the first occurrence, not the last one and lastIndexOf accepts value while in my case it should be the last element with given length.
let variables = ['A', 'B', 'C', 'D', 'AA', 'AB'];
const nextVariable = 'E';
const idx = variables.findIndex(x => x.length === nextVariable.length);
variables.splice(idx, 0, nextVariable);
console.log(variables);
// should be ['A', 'B', 'C', 'D', 'E', 'AA', 'AB']
You can just look for the first variable which is longer than the variable to insert, and if it doesn't exist (findIndex returns -1), add to the end of the array:
let variables = ['A', 'B', 'C', 'D', 'AA', 'AB'];
let nextVariable = 'E';
let idx = variables.findIndex(x => x.length > nextVariable.length);
variables.splice(idx < 0 ? variables.length : idx, 0, nextVariable);
// should be ['A', 'B', 'C', 'D', 'E', 'AA', 'AB']
console.log(variables);
nextVariable = 'AC';
idx = variables.findIndex(x => x.length > nextVariable.length);
variables.splice(idx < 0 ? variables.length : idx, 0, nextVariable);
// should be ['A', 'B', 'C', 'D', 'E', 'AA', 'AB', 'AC']
console.log(variables);
let variables = ['A', 'B', 'C', 'D', 'AA', 'AB'];
const nextVariable = 'E';
variables[variables.length] = nextVariable
variables = variables.sort((x,y) => x.length<y.length ? -1 : x.length==y.length ? x.localeCompare(y) : 1)
console.log(variables);
You can use a custom sort function and test the alphabetical order and length of each value.
function mySort(a, b) {
if(a.length == b.length) {
return a.localeCompare(b);
} else {
return a.length - b.length;
}
}
The you can use this function to sort the array after a new value has been added:
variables.sort(mySort);
I want to get the exact difference between two string arrays.
const array1 = ['T','E','A','P','A','P','E','R'];
const array2 = ['T','A','P'];
Expected Output Array:
['E','A','P','E','R']
I have tried this method:
const output = array1.filter(char => array2.includes(char));
But that removes all instances of a character, like:
['E','E','R']
I'm a newbie, so could you guide me to the right direction?
You could take a closure over the index for the second array and increment the index and remove this item from the result set.
var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
array2 = ['T', 'A', 'P'],
result = array1.filter((i => v => array2[i] !== v || !++i)(0));
console.log(result);
A different approach without a predefined order of array2.
var array1 = ['T', 'E', 'A', 'P', 'A', 'P', 'E', 'R'],
array2 = ['T', 'A', 'P'],
set2 = new Set(array2)
result = array1.filter(v => !set2.delete(v));
console.log(result);
You could remove elements from allowed based on the input array:
const allowed = ['T','E','A','P','A','P','E','R'];
const input = ['T','A','P'];
for(const char of input) {
const pos = allowed.indexOf(char);
if(pos === -1) {
// char doesnt exist?
} else {
allowed.splice(pos, 1);
}
}
Then allowed will be your expected result at the end.
I think filter is not correct apparoch here. Because there are some elements repeadted. Use a simple for-loop. And remove the elements when you add it to result.
const array1 = ['T','E','A','P','A','P','E','R'];
const array2 = ['T','A','P'];
const copy = [...array2];
let res = [];
for(let i = 0;i<array1.length;i++){
let index = copy.indexOf(array1[i]);
if(index === -1){
res.push(array1[i]);
}
else copy.splice(index,1);
}
console.log(res)
Consider the following arrays:
['a', 'b', 'a'] //method should return true
['a', 'b', 'c'] //method should return true
['a', 'c', 'c'] //method should return false
I want to write a method that most efficiently checks to see if both 'a' and 'b' exist in the array. I know I can do this in a simple for loop
let a_counter = 0;
let b_counter = 0;
for (let i = 0; i < array.length; i++) {
if (array[i] === 'a') {
a_counter++;
}
if (array[i] === 'b') {
b_counter++;
}
}
return (a_counter > 0 && b_counter > 0);
But this isn't very short. I can do indexOf but that will loop through twice. I have also considered using a set as below:
const letter_set = new Set(array)
return (letter_set.has('a') && letter_set.has('b'))
But I am pretty unfamiliar with sets and don't know if this solution could potentially be more expensive than just looping. I know that has() operations should be faster than array iterations but constructing the set probably takes at least O(N) time (I'm assuming).
Is there a clean and efficient way to find multiple elements in an array? ES6 answers welcome
You can use every and includes to do this check.
So we are saying every item must be included in the array.
function contains(arr, ...items) {
return items.every(i => arr.includes(i))
}
console.log(contains(['a', 'b', 'a'], 'a', 'b'))
console.log(contains(['a', 'c', 'c'], 'a', 'b'))
console.log(contains(['a', 'b', 'c'], 'a', 'b', 'c'))
console.log(contains(['a', 'b', 'c', 'd'], 'a', 'b', 'c', 'd', 'e'))
You could use just the Set and check if the wanted items are in the items array.
const
check = (items, wanted) => wanted.every(Set.prototype.has, new Set(items));
console.log(check(['a', 'b', 'a'], ['a', 'b'])); // true
console.log(check(['a', 'b', 'c'], ['a', 'b'])); // true
console.log(check(['a', 'c', 'c'], ['a', 'b'])); // false
array.includes('a') && array.includes('b')
includes seems like a real handy way to check for specific elements, even if there is more than one.
Not as compact as the other examples, but it does do the job in single run.
const arr1 = ['a', 'b', 'a']; //method should return true
const arr2 = ['a', 'c', 'c']; //method should return false
const arr3 = ['a', 'b', 'c']; //method should return true
const reducer = ({ a, b }, char) => ({
a: a || char === 'a',
b: b || char === 'b'
});
const includesAnB = arr => {
const { a, b } = arr.reduce(reducer, {});
return a && b;
}
console.log(includesAnB(arr1));
console.log(includesAnB(arr2));
console.log(includesAnB(arr3));
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);
}