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.

4
  • Could you add the HTML to the question so we can create a working example Commented Sep 3, 2019 at 15:10
  • i just wanted to create that values from the two arrays Commented Sep 3, 2019 at 15:13
  • You can use two nested loops, that would be the simplest solution. Commented Sep 3, 2019 at 15:14
  • Possible duplicate of JavaScript - Generating combinations from n arrays with m elements Commented Sep 3, 2019 at 15:16

2 Answers 2

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)

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

1 Comment

Thanks, how about you for multiple arrays?
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);

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.