# Add all records from one array to each record from a different array in JavaScript

The problem statement asks the user to add all the records from one array to each record from a different array in JavaScript , the just read statement seems tough to understand and implement code upon . The simplest meaning is given two arrays of different collections of values , we need to generate a combined new array of objects such that the new generated array is a collection of every possible of values present in both arrays for say array1 and array2.

The problem statement can be implemented in another way too , saying to find the Cartesian Product of two arrays given as an input by the user .

## What is a Cartesian Product in JavaScript ?

Cartesian Product is actually a concept of mathematics set theory where given two sets A and B , A *B is the every possible combination of sets where the values of it are present in either A or B , here the problem statement replaces the states with the input arrays given by the user.

In JavScript , the code logic sees Cartesian Product as a problem statement whose solution has a fundamental pillar of traversing each and every element of both the arrays followed by paring every element of the first array with every element of the second array.

The visual of the solution in respect to problem statement looks like :

Given two arrays :

const array1 = [ 1, 2 , 3 ];
const array2 = [ 'x' ,'y' , 'z' ] ;

const caretsianProductofArrays = [ [1,'x'] , [1,'y''] , [1,'z'] , [2,'x'] ,
[2,'y'] , [2,'z'] , [3,'x'] , [3,'y'] , [3,'z'] ];


## Algorithm - Using loop

The algorithm follows on the core logic of possibly forming each and every ordered pair from the given input of two arrays.

Step 1 : Declare a function with name combineTwoArrayRecords that takes array1 and array2 as an input .

Step 2 : Declare and initialize the resultant array naming resultArr as an empty array .

Step 3 : We use foreach loop to traverse the elements through an array that uses foreach loop as the callback function to generate every possible pair of callback foreach for every iteration of the outer foreach loop thus generating possible combinations of array elements.

Step 4 : To convert the array of arrays into the array of objects , we have passed the key and value parameter inside the push method for each iteration to make it mold all the possible combinations of each and every element of both arrays into key-value pairs and object of arrays form.

Step 5 : Once the length of all the arrays are exhausted till the length property of the javascript , we return back the resultant object containing every possible combination of elements present in both arrays in key and value pair form.

### Example

function combineTwoArrayRecords(arr1 , arr2)
{
let resultArr =[];
arr1.forEach(itemArr1 => {
arr2.forEach(itemArr2 =>{
resultArr.push({
'User' : itemArr1 ,
'City' : itemArr2
})
})
})
return resultArr;
}

const nameArray = [ "Michael" , "James" ,"Steve"];
const cityArray = [ "NewYork" , "Japan" , "USA" ,"China"]

const finalCombinations = combineTwoArrayRecords( nameArray , cityArray);

console.log(finalCombinations);


### Output

[
{ User: 'Michael', City: 'NewYork' },
{ User: 'Michael', City: 'Japan' },
{ User: 'Michael', City: 'USA' },
{ User: 'Michael', City: 'China' },
{ User: 'James', City: 'NewYork' },
{ User: 'James', City: 'Japan' },
{ User: 'James', City: 'USA' },
{ User: 'James', City: 'China' },
{ User: 'Steve', City: 'NewYork' },
{ User: 'Steve', City: 'Japan' },
{ User: 'Steve', City: 'USA' },
{ User: 'Steve', City: 'China' }
]


This is one of the easiest methods to add all the records from one array to each record in a different array in javascript using a nested loop but time complexity in such an algorithm suffers a lot.

## Time and Space Complexity

Because of the two loops present in the algorithm , we experience a quadratic worst time complexity of O(n^2) but remember two arrays are not of the same length such that array1 is of length m size and array2 is of length n size with the possibility of m>n or m<n or m=n . So the time complexity is O(mn) dependent on the length of both array1 and array2. The space complexity is O(1) because of no extra allocation of memory.

## Algorithm - Using Map and Reduce Method

Step 1 : Declare a function with name combineArrayOfRecords that takes array1 and array2 as an input source given by the user .

Step 2 : Return a reducer function applied on array1 such that the reducer function takes accumulator and current value as the parameter using which the reducer function is actually executed on each member of the calling array which results in a single output value ie, the one possible combination we need for the problem statement to solve for.

Step 3: Accumulator present in the parameter takes first value of the array1 if no initial value os provided and current Value takes the second one such that inside it the map function is applied on array2 is used to map each and every element of array2 on the every member of array1 which called the reducer function molding in key and value pair form of Users and City.

Step 4: This is how the accumulator will store each and every possible combination of elements made using reduce and map function through spread operator and different records of each array is generated solving the problem statement .

## Main Code - Using Map and Reduce Method

### Example

function combineArrayOfRecords(arr1,arr2)
{
return arr1.reduce((accumulator , currentValue)=>

[...accumulator , ...arr2.map(currentItem=>(

{
'User' : currentValue ,
'City' : currentItem
}
))]

, [])
}

const nameArray = [ "Michael" , "James" ,"Steve"]
const cityArray = [ "NewYork" , "Japan" , "USA" ,"China"]
const finalArray = combineArrayOfRecords(nameArray , cityArray);
console.log(finalArray);



### Output

[
{ User: 'Michael', City: 'NewYork' },
{ User: 'Michael', City: 'Japan' },
{ User: 'Michael', City: 'USA' },
{ User: 'Michael', City: 'China' },
{ User: 'James', City: 'NewYork' },
{ User: 'James', City: 'Japan' },
{ User: 'James', City: 'USA' },
{ User: 'James', City: 'China' },
{ User: 'Steve', City: 'NewYork' },
{ User: 'Steve', City: 'Japan' },
{ User: 'Steve', City: 'USA' },
{ User: 'Steve', City: 'China' }
]


## Time and Space Complexity

The minimum time complexity of the reduce function is O(n) because the array1 is calling it iterating through the length of the array at its worst case . Even inside the every call to each member of elements of array1 , map is called on array traversing through the length of array taking O(n) time complexity summing up to O(n) + O(n) = O(n) time complexity. The space complexity is O(1) because of no extra allocation of memory.

## Conclusion

This is how we can solve the above problem statement thinking logically and in the context of coding going from nested foreach loops to the reduce and map methods of javascript in its most efficient use case .

Updated on: 22-Aug-2023

271 Views