1

I need to create one single array from 3 arrays,

I already implemented the logic and it's working but i think with Array.prototype i can achieve the same with better performance

let classrooms = [
    1,
    2
]
let modules = [
    5,
    6
]

let weeks = [
   7,
   8
]

let avalArray = [];
classrooms.forEach(classroomId => {
        modules.forEach(moduleId => {
            weeks.forEach(week => {
                avalArray.push({
                    classroomId: classroomId,
                    moduleId: moduleId,
                    week: week
                });
            });
        });
    }); 

This is the expected output:

[ { classroomId: 1, moduleId: 5, week: 7 },
  { classroomId: 1, moduleId: 5, week: 8 },
  { classroomId: 1, moduleId: 6, week: 7 },
  { classroomId: 1, moduleId: 6, week: 8 },
  { classroomId: 2, moduleId: 5, week: 7 },
  { classroomId: 2, moduleId: 5, week: 8 },
  { classroomId: 2, moduleId: 6, week: 7 },
  { classroomId: 2, moduleId: 6, week: 8 } ] ```
mpardo
  • 13
  • 3
  • this might help: https://stackoverflow.com/questions/12303989/cartesian-product-of-multiple-arrays-in-javascript – georg Jun 27 '19 at 17:04

3 Answers3

0

This is a more functional solution that uses Array.flatMap() with Array.map() to generate the array of objects.

However, I think that your performance should be better, since yours doesn't generate temporal arrays that are then flattened to other temporal arrays, that are flattened to a single array.

const classrooms = [1, 2]
const modules = [5, 6]
const weeks = [7, 8]

const result = classrooms.flatMap(classroomId =>
  modules.flatMap(moduleId =>
    weeks.map(week => ({
      classroomId,
      moduleId,
      week
    }))))
    
console.log(result)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
0

You can use map and flat. It will be more compact, but it will be very slow. Use for loop for better performance.

classrooms .map(classroomId => modules .map(moduleId => weeks.map(week => ({classroomId, moduleId, week}))) ).flat(2)

0

There was a request some time ago for the cartesian product back in #852 (January 2015!). As you see, it's not implemented.

As the others said, performing a simple loop without external arrays will definitely be faster. To be sure: just benchmark it. I've prepared a simple suite on perf.link and here are the results:

for-loop:         175us
for-of-loop:      175us
forEach:          290us
map-map-map-flat: 465us
flatMap:          5635us

Exact numbers are not important here, but here's one takeaway: for-of loop (not transpiled!) is one of the fastest and still very elegant:

const result = [];
for (const classroomId of classrooms)
  for (const moduleId of modules)
    for (const week of weeks)
      result.push({classroomId, moduleId, week});
Radosław Miernik
  • 4,004
  • 8
  • 33
  • 36