简体   繁体   中英

Javascript program to find combination of length 2 for two arrays of different lengths

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM