Skip to content
Advertisement

Two arrays of varying lengths, each object in array_1 must get a copy of each object in array_2

We have two arrays that are based on the results of two MySQL SELECT queries, array_1 looks something like this:

[{studentID: "138"}, {studentID: "151"}]

And array_2 looks like something this:

[{pacesetterID: “218”}, {pacesetterID: “219”}, {pacesetterID: “221”}, {pacesetterID: “220”}, {pacesetterID: “222”}]

I need to end up with a single array where each object in array_1 has a copy of each object in array_2. I.e. each “studentID” gets a copy of every “pacesetterID”. I’ve tried forEach looping, but if array_1 has, let’s say 2 objects, only 2 objects from array_2 are copied.

Both arrays can vary in length, each will have a minimum length of 1 objects but a maximum of anywhere from 40-50 objects.

How can I achieve this? Here is an idea of what I need to achieve based on the two arrays provided:

[{pacesetterID: “218”, studentID: “138”}, {pacesetterID: “219”, studentID: “138”}, {pacesetterID: “221”, studentID: “138”}, {pacesetterID: “220”, studentID: “138”}, {pacesetterID: “222”, studentID: “138”}, {pacesetterID: “218”, studentID: “151”}, {pacesetterID: “219”, studentID: “151”}, {pacesetterID: “221”}, {pacesetterID: “220”, studentID:” 151”}, {pacesetterID: “222”, studentID: “151”}]

Advertisement

Answer

It can be done using two loops and saving the result into a third variable.

let arr1 = [{studentID: "138"}, {studentID: "151"}];
let arr2 = [{pacesetterID: '218'}, {pacesetterID: '219'}, {pacesetterID: '221'}, {pacesetterID: '220'}, {pacesetterID: '222'}];
let arr3 = [];

for(let i=0; i<arr1.length; i++){
  for(let j = 0; j<arr2.length; j++){
    arr3.push({...arr2[j], ...arr1[i]});
  }
}

console.log(arr3);
Advertisement