0

I am doing a script in jQuery where it will create a sku_values for the variant items. I've managed to create an array for the items require in my sku.

[78,79,80] - item value for the first variant
[81,82] - item value for the 2nd

so what i want to do is create a concatenate value for these arrays

var variant_items = [];
if ($("input[name*='variant']").length > 0) {
   $("input[name*='variant']").each(function(index, variant){   
   variant_items[index] = [];
   var data = $(variant).data();
   if($('ul[data-variant-id='+data.variantId+'] li').length > 0){
    $('ul[data-variant-id='+data.variantId+'] li').each(function(i, item){                           
      variant_items[index].push($(item).data('item-id'));
    });
   }
 });
}

my expected output is

78_81
78_82
79_81
79_82
80_81
80_82

which is hard for me to solve the problem.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
nikcoder
  • 11
  • 3

2 Answers2

4

use flatMap

const a1 = [78,79,80]
const a2 = [81,82]

const ans = a1.flatMap(e1 => a2.map(e2 => e1 + `_` + e2))

console.log(ans)

for an arbitrary number of arrays use recursion

const a1 = [77, 78, 79, 80]
const a2 = [81, 82, 83]
const a3 = [84, 85]

const conc = (a, ...as) => 
  as.length === 0 ? a : a.flatMap(e1 => conc(...as).map(e2 => e1 + `_` + e2))

const ans = conc(a1, a2, a3)

console.log(ans)
marzelin
  • 10,790
  • 2
  • 30
  • 49
0

You can use Array.map and Array.reduce

var arr1 = [78,79,80];
var arr2 = [81,82];

var output = arr1.map(function(e){
    return arr2.map(function(ee){
        return `${e}_${ee}`;
    })
}).reduce(function(acc, e){    
    return acc = acc.concat(e);
}, []);
console.log(output);
Eric
  • 573
  • 1
  • 5
  • 11