Home > Back-end >  combine array elements and send response in javascript
combine array elements and send response in javascript

Time:05-31

I have two arrays

[a1,a2,a3] and [d1,d2,d3]

I want my request object to be

```{
 appid:a1,
 dataid:d1
},
{appid:a1,
 dataid:d2
},
{appid:a1,
 dataid:d3
},
{appid:a2,
 dataid:d1
},
{appid:a2,
 dataid:d2
},
{appid:a2,
 dataid:d3
},
{appid:a3,
 dataid:d1
},
{appid:a3,
 dataid:d2
},
{appid:a3,
 dataid:d3
}```

any help is appreciated. Going ahead arrays might get dynamic and need to do the logic dynamically but for now I want it for above mentioned array.

CodePudding user response:

This is a Cartesian product:

const cartesian = (a, b) => a.flatMap(appid => b.map(dataid => ({appid, dataid})));

console.log(cartesian(["a", "b", "c"], [1, 2, 3]));

CodePudding user response:

let combinedArray = [];
array1.forEach((element, index) => {
    let batch = [];
    array2.forEach((element2, index2) => {
         batch.push({
              appid: element,
              dataid: element2
         });
    });
    combinedArray.push(...batch);
});

Something along these lines. Seems like the easiest way to do this assuming arrays are the same length and in the right order. You can use for loop instead.

Actually, that doesn't seem like the right solution either. I'm not sure what pattern you are trying to achieve with your example, so I will leave it like this. You can adjust the algorithm to your needs.

Edited because I re-read the question.

CodePudding user response:

[].concat.apply([],[1,2,3].map(x => [1,2,3].map(y=> { return {'a': x, 'b':y}})))

CodePudding user response:

Const arr1 = [a1, a2, a3];
Const arr2 =[d1, d2, d3];
Const arr3 = [];

for(let i = 0;i<arr1.length;i  ){
  for(let b=0;b<arr2.length;b  ){
   return arr3.push({appid: arr1[i], dataid: arr2[b] })
}
}
  • Related