knot22
knot22

Reputation: 2768

ES6 equivalent to SQL cross join

Is there a way in JS to take these two arrays, scenarios and items, and essentially cross join them to end up with the output shown in result?

const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const result = [
    'a/2020-12-01/201/17', 'a/2020-12-01/201/28', 'a/2020-12-01/207/3', 'a/2020-12-01/208/4', 'a/2020-12-01/208/12',
    'b/2020-12-04/201/17', 'b/2020-12-04/201/28', 'b/2020-12-04/207/3', 'b/2020-12-04/208/4', 'b/2020-12-04/208/12'
];

I have had no success searching online for how to do this - possibly because I don't know the correct name for what this is in JS terminology.

Upvotes: 1

Views: 148

Answers (2)

Majed Badawi
Majed Badawi

Reputation: 28414

You can do this with .reduce and .map as follows:

const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const res = scenarios.reduce((acc,scen) => {
  acc.push(
    ...items.map(item => `${scen}/${item}`)
  );
  return acc;
}, []);

console.log(res);

Another simple solution using two for-loops:

const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const res = [];

for(let i = 0; i < scenarios.length; i++)
  for(let j = 0; j < items.length; j++)
    res.push(`${scenarios[i]}/${items[j]}`);

console.log(res);

Upvotes: 4

Ori Drori
Ori Drori

Reputation: 191976

Use Array.flatMap() to iterate the scenarios and flatten the results, with Array.map() to iterate the items, and combine them with the scenarios:

const scenarios = ['a/2020-12-01', 'b/2020-12-04'];
const items = ['201/17', '201/28', '207/3', '208/4', '208/12'];

const res = scenarios.flatMap(scen =>
  items.map(item => `${scen}/${item}`)
);

console.log(res);

Upvotes: 3

Related Questions