-2

I have N arrays with objects inside. All objects has the same keys.

arr[
   {values:val1,names:someName},
   {values:val2,names:otherName},
]
arr2[
   {values:valx,names:someNamex},
   {values:valy,names:otherNamey},
]

I need to mix all the combinations between that N arrays. Something like this:

newArray[
{values:'val1''valx',names:'someName''someNamex'}
{values:'val1''valy',names:'someName''someNamey'}
{values:'val2''valx',names:'otherName''someNamex'}
{values:'val2''valy',names:'otherName''someNamey'}
]

I hope this can be helpful to find an answer to this problem.

Thanks for your time!

baconitus
  • 35
  • 4
  • Please show us what you have attempted. – Luke Vo May 03 '22 at 20:19
  • comb(arr: string | any[], pre?: string | undefined) { pre = pre || ' '; if (!arr.length) { return pre; } var ans = arr[0].reduce((ans: string | any[], value: string | any) => { return ans.concat(this.comb(arr.slice(1), pre + value)); } , []); return ans; } – baconitus May 03 '22 at 20:28
  • 1
    Does this answer your question? [Cartesian product of multiple arrays in JavaScript](https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript) – pilchard May 03 '22 at 20:50

1 Answers1

1

Presented below is one possible way to achieve the desired objective.

Code Snippet

const myArr1 = [
   {values:'val1',names:'someName'},
   {values:'val2',names:'otherName'},
];
const myArr2 = [
   {values:'valx',names:'someNamex'},
   {values:'valy',names:'otherNamey'},
];

const arrOfArr = [...Array(5).keys()].map(x => (
  [...Array(3).keys()]
  .map(k => ({
    values: `val${x}${k}`,
    names: `someName${x}${k}`
  }))
));
//console.log(...arrOfArr);

const myConcat = (a, b, ...objs) => (
  objs.flatMap((obj) => ({
    values: `${a.values} ${b.values}`,
    names: `${a.names} ${b.names}`
  }))
);
const f = (a, b) => [].concat(...a.flatMap(d => b.flatMap(e => myConcat(d, e, []))));
const cartesian = (a, b, ...c) => (b ? cartesian(f(a, b), ...c) : a);

console.log(
  'simple test case with only 2 arrays: ', cartesian(myArr1, myArr2), '\n\n\t******\n\n'
);
console.log(
  'complex test case with 7 arrays some with 3 objects each: ',
  cartesian(myArr1, myArr2, ...arrOfArr)
);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Explanation

  • Adapts the cartesian-product answer as noted by pilchard to this context
  • Invokes the cartesian method for given set of arrays
  • Uses .myConcat() to transform the result of concatenation to have values and names string-concatenated at a per-object level
jsN00b
  • 3,584
  • 2
  • 8
  • 21