2

I have 3 or more array :

 var array1 = [a,b,c];
 var array2 = [c,d];
 var array3 = [e,f];

Want to get 1 merged array with the result like this one:

result = [ace, acf, ade, adf, bce, bdf, bde, bdf, cce, ccf, cde, cdf]

How can I do it? Please note: array input will not limit.

2
  • 2
    It seems your looking for all combinations, not a "merge". Commented Oct 17, 2016 at 7:09
  • I agree, that's not .concat() you're looking for. Commented Oct 17, 2016 at 7:10

6 Answers 6

4

You could use an iterative and recursive approach with a combination algorithm.

function combine(array) {
    function c(part, index) {
        array[index].forEach(function (a) {
            var p = part.concat([a]);
            if (p.length === array.length) {
                r.push(p.join(''));
                return;
            }
            c(p, index + 1);
        });
    }

    var r = [];

    c([], 0);
    return r;
}

console.log(combine([['a', 'b', 'c'], ['c', 'd'], ['e', 'f']]));
console.log(combine([['a', 'b', 'c'], ['d', 'e'], ['f', 'g'], ['h', 'i', 'j']]));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sign up to request clarification or add additional context in comments.

Comments

2

Try using for loop Jsfiddle

var array1 = ["a", "b", "c"];
var array2 = ["c", "d"];
var array3 = ["e", "f"];
var result = [], pushresult = 0;

for (var i = 0; i < array1.length; i++) {
  for (var j = 0; j < array2.length; j++) {
    for (var k = 0; k < array3.length; k++) {
      pushresult = array1[i] + array2[j] + array3[k];
      result.push(pushresult);
    }
  }
}

console.log(result);

4 Comments

Why post elsewhere when you can make your code a runnable snippet here?
Ya. But, I don't know how to do it. :(
@priya_singh for you reference Format code blocks
Thank for your help. But if i have 4, 5 or 100 arrays like that, i have to use 100 time loop? :((. Thank you so much :)
2

It seems that you are trying to get the Cartesian product from multiple arrays(sets).
Consider the following ES6 solution using Array.concat, Array.reduce and Array.map functions:

const flatten = (arr) => [].concat.apply([], arr);
const product = (...sets) =>
    sets.reduce((acc, set) =>
            flatten(acc.map(x => set.map(y => [ ...x, y ]))),
    [[]]);

var array1 = ['a', 'b', 'c'],
    array2 = ['c','d'],
    array3 = ['e','f'];

result = product(array1, array2, array3);

console.log(JSON.stringify(result));

1 Comment

Up-voting this for identifying catesian product.
0
if you number of array is fixed (not array element) then you can use

<script>
var array1 = ["a","b","c"];
var array2 = ["c","d"];
var array3 = ["e","f"];
var d=[];
for(i in array1){
    for (j in array2){
        for(k in array3){
        d.push(array1[i]+array2[j]+array3[k]);  
        }
    }
}
alert(d);
</script>

1 Comment

for..in is more suited for looping over objects
0

It seems you need an Array.prototype.cartesian() for indefinite number of arrays. It can be done as follows;

Array.prototype.cartesian = function(...a){
  return a.length ? this.reduce((p,c) => (p.push(...a[0].cartesian(...a.slice(1)).map(e => a.length > 1 ? [c,...e] : [c,e])),p),[])
                  : this;
};

var arr1 = ["a","b","c"],
    arr2 = ["c","d"],
    arr3 = ["e","f"],
  result = arr1.cartesian(arr2,arr3);
console.log(JSON.stringify(result));

Comments

0

The List applicative and monad can achieve this with ease

// Array Applicative  
Array.prototype.ap = function ( ...args )
  {
    const loop = ( acc , [ x , ...xs ] ) =>
      x === undefined
        ? [ this [ 0 ] ( ...acc ) ]
        : x.chain ( a =>
            loop ( acc.concat ( [ a ] ) , xs ) )
    return loop ( [] , args )
  }
 
// Array Monad
Array.prototype.chain = function chain (f)
  {
    return this.reduce ( ( acc , x ) =>
      acc.concat ( f (x) ), [] )
  }

// the hard work is already done
const combinations = ( ...xxs ) =>
  [ ( ...xs ) => xs ] .ap ( ...xxs )

console.log ( combinations ( array1 , array2 , array3 ) )
// [ [ 'a1', 'a2', 'a3' ],
//   [ 'a1', 'a2', 'b3' ],
//   [ 'a1', 'a2', 'c3' ],
//   [ 'a1', 'b2', 'a3' ],
//   [ 'a1', 'b2', 'b3' ],
//   [ 'a1', 'b2', 'c3' ],
//   [ 'b1', 'a2', 'a3' ],
//   [ 'b1', 'a2', 'b3' ],
//   [ 'b1', 'a2', 'c3' ],
//   [ 'b1', 'b2', 'a3' ],
//   [ 'b1', 'b2', 'b3' ],
//   [ 'b1', 'b2', 'c3' ],
//   [ 'c1', 'a2', 'a3' ],
//   [ 'c1', 'a2', 'b3' ],
//   [ 'c1', 'a2', 'c3' ],
//   [ 'c1', 'b2', 'a3' ],
//   [ 'c1', 'b2', 'b3' ],
//   [ 'c1', 'b2', 'c3' ],
//   [ 'd1', 'a2', 'a3' ],
//   [ 'd1', 'a2', 'b3' ],
//   [ 'd1', 'a2', 'c3' ],
//   [ 'd1', 'b2', 'a3' ],
//   [ 'd1', 'b2', 'b3' ],
//   [ 'd1', 'b2', 'c3' ] ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.