I have two array ['b','c','d','e']
& ['h','i','k','l','m','n']
I want to find combinations of length 2 for array above using Javascript/AngularJS program. eg
['bh','bi','bk','bk','bl','bm','bn','ch,'ci','ck' ...]
Here is functional programming ES6 solution:
var array = ['b','c','d','e']; var array2 = ['h','i','k','l','m','n']; var result = array.reduce( (a, v) => [...a, ...array2.map(x=>v+x)], []); console.log(result); /*---------OR--------------*/ var result1 = array.reduce( (a, v, i) => a.concat(array2.map( w => v + w )), []); console.log(result1); /*-------------OR(without arrow function)---------------*/ var result2 = array.reduce(function(a, v, i) { a = a.concat(array2.map(function(w){ return v + w })); return a; },[] ); console.log(result2); /*----------for single array------------*/ var result4 = array.reduce( (a, v, i) => [...a, ...array.slice(i+1).map(x=>v+'-'+x)], []); console.log(result4);
Use nesting Array.map()
calls and combine the letters. Flatten the arrays by spreading into Array.concat()
:
const arr1 = ['b','c','d','e']; const arr2 = ['h','i','k','l','m','n']; const result = [].concat(...arr1.map((l1) => arr2.map((l2) => l1 + l2))); console.log(result);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.