javascript - Finding all combination sequences from array in JS -


disclaimer: know part of question has been asked , answered here before , yes, have helped me point far.

let's have array contains 2 elements , want find possible combinations made of these elements. order of sets not matter.

var myarr = ['a','b'];

desired result

var result = [ [a], [a,b], [b], [b,a] ]

at first thought looking power set not want null set , want treat [a,b] , [b,a] unique sequences not equals. more info sets, null set, , equal sets here.

so far have written function recursively loop through array, create new arrays each possible combinations , push them results array.

function getcombinations() {      var myarr = ['a','b'],     result = [];      var recurfn = function(prefix, myarr) {          (var = 0; < myarr.length; i++) {              var newarray = prefix !== '' ? [prefix, myarr[i]] : [myarr[i]];             result.push(newarray);         recurfn(prefix + myarr[i], myarr.slice(i + 1));         }     }      recurfn('', myarr);     console.log(result); //[[a], [a,b], [b]]  } 

here fiddle above code.

currently returning 3 possible combinations [a], [a,b], [b], how can edit code returning [a], [a,b], [b], [b,a].

thanks!

can make 2 arrays in reverse order:

var myarr = ['a','b'] var myarr2 = ['b','a']  var recurfn = function(prefix, myarr) {      (var = 0; < myarr.length; i++) {          var newarray = prefix !== '' ? [prefix, myarr[i]] : [myarr[i]];         result.push(newarray);     recurfn(prefix + myarr[i], myarr.slice(i + 1));     }     (var = 0; < myarr2.length; i++) {          var newarray2 = prefix !== '' ? [prefix, myarr2[i]] : [myarr2[i]];         result.push(newarray2);     recurfn(prefix + myarr2[i], myarr2.slice(i + 1));     } newarray.concat(newarray2); newarray.unique();  } 

Comments

Popular posts from this blog

angular - Is it possible to get native element for formControl? -

unity3d - Rotate an object to face an opposite direction -

javascript - Why jQuery Select box change event is now working? -