Skip to content Skip to sidebar Skip to footer

How To Take Two Arrays Of Strings To Build Out A Array That Combines Them All?

I have a part numbers array, ['PCI-33', 'GG-34', 'GG-32'] and I have an array of zones, ['UK', 'US', 'CA', 'MX'] etc. I'm trying to combine both of these arrays so I can get somet

Solution 1:

Use 2 nesting Array#map to create combine the two array, and apply Array#concat to flatten the results:

var strs1 = ['PCI-33', 'GG-34', 'GG-32'];
var strs2 = ['UK', 'US', 'CA', 'MX'];

var result = [].concat.apply([], strs1.map(function(str1) {
  return strs2.map(function(str2) {
    return str1 + '-' + str2;
  });
}));

console.log(result);

And the ES6 version that uses Array#concat with the spread syntax to flatten the sub arrays, and a template literal to create the strings.

var strs1 = ['PCI-33', 'GG-34', 'GG-32'];
var strs2 = ['UK', 'US', 'CA', 'MX'];

var result = [].concat(...strs1.map((str1) => strs2.map((str2) =>`${str1}-${str2}`)));

console.log(result);

Solution 2:

Cartesian product is the mathematical term for this type of combination.

If you're not comfortable with using the "fancier" array methods, a simple way to do this is to use a nested for loop:

var parts = ['PCI-33', 'GG-34', 'GG-32'],
    zones = ['UK', 'US', 'CA', 'MX'];

var combined = [];
for(var i = 0; i < parts.length; i++) {
    for(var j = 0; j < zones.length; j++) {
        combined.push(parts[i] + "-" + zones[j]);
    }
}

Then combined will contain

["PCI-33-UK", "PCI-33-US", "PCI-33-CA", "PCI-33-MX", "GG-34-UK", "GG-34-US", "GG-34-CA", "GG-34-MX", "GG-32-UK", "GG-32-US", "GG-32-CA", "GG-32-MX"]

Solution 3:

ES-1999 code with 1 loop:

var codes = ['PCI-33', 'GG-34', 'GG-32'];
var zones = ['UK', 'US', 'CA', 'MX'];
var arr = [];

var cl = codes.length;

for (var i=0; i < cl * zones.length; i++) {
  arr.push(codes[i % cl] + "-" + zones[Math.floor(i / cl)]);
}

console.log(arr);

Solution 4:

You may also do as follows;

functioncombine(a,[b,...bs]){
  return [a + "-" + b].concat(bs.length ? combine(a,bs) : []);
}

var arr = ['PCI-33', 'GG-34', 'GG-32'],
    brr = ['UK', 'US', 'CA', 'MX'],
    res = functionrunner([a,...as],bs){
            returncombine(a,bs).concat(as.length ? runner(as,bs) : []);
          }(arr,brr); // Recursive IIFE hereconsole.log(res);

Post a Comment for "How To Take Two Arrays Of Strings To Build Out A Array That Combines Them All?"