-1

Can anybody please help me generate a new array from an existing array. Here's my array (sample)

[
 1,
 2,
 [3,4],
 9
 [5,6],
 [7,8]
]

And here's what i want to achieve

[
 [1,2,3,9,5,7],
 [1,2,4,9,5,7],
 [1,2,3,9,6,7],
 [1,2,4,9,6,7],
 [1,2,3,9,5,8],
 [1,2,4,9,5,8],
 [1,2,3,9,6,8],
 [1,2,4,9,6,8]
]

Thanks

Edit Because I want to make a proper combination of the nested array. I dont think this question will help.

str
  • 42,689
  • 17
  • 109
  • 127
Wdy Dev
  • 219
  • 2
  • 11

2 Answers2

1

This looks like Cartesian product so you could create recursive function for that.

var data = [ 1, 2, [3,4], 9, [5,6], [7,8] ];

function convert(data, n = 0, c = [], r = []) {
  if(n == data.length) return r.push(c.slice());
  let el = Array.isArray(data[n]) ? data[n] : [data[n]]
  for(var i = 0; i < el.length; i++) {
    c[n] = el[i];
    convert(data, n + 1, c, r);
  }
  return r;
}

console.log(JSON.stringify(convert(data)))
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

Another approach that creates first element from first elements in data, then maps new arrays from that base in reduce()

var data = [1, 2, [3, 4], 9, [5, 6],  [7, 8]];

const base = data.map(e => Array.isArray(e) ? e[0] : e);
const res = data.reduce((a, el, dIdx) => {
  if (Array.isArray(el)) {
    let newArrs = el.slice(1).map(nVal => {
      return [...a.map(arr => arr.map((val, i) => i === dIdx ? nVal : val))];
    })
    return a.concat(...newArrs)
  }
  return a;
}, [base]);

console.log(JSON.stringify(res))
charlietfl
  • 170,828
  • 13
  • 121
  • 150