Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
464 views
in Technique[技术] by (71.8m points)

javascript - Javascript程序为两个不同长度的数组找到长度2的组合(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.

(我有两个数组['b','c','d','e']['h','i','k','l','m','n']我想使用Javascript / AngularJS程序在上面的数组中找到长度为2的组合。)

eg

(例如)

['bh','bi','bk','bk','bl','bm','bn','ch,'ci','ck' ...]
  ask by neha translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Here is functional programming ES6 solution:

(这是功能编程 ES6解决方案:)

 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); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...