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

In JavaScript, you may need to combine elements from two arrays where each record from one array pairs with every record from another array. This creates a Cartesian product - every possible combination of elements from both arrays.

What is a Cartesian Product?

A Cartesian product is a mathematical concept where given two sets A and B, A × B represents every possible combination of elements from both sets. In JavaScript, this translates to pairing each element from the first array with every element from the second array.

For example, given two arrays:

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

// Cartesian Product: [[1,'x'], [1,'y'], [1,'z'], [2,'x'], [2,'y'], [2,'z'], [3,'x'], [3,'y'], [3,'z']]

Using Nested Loops

The most straightforward approach uses nested loops to iterate through both arrays:

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);
[
  { 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' }
]

Using Array Methods (Map and Reduce)

A more functional approach uses reduce() and map() methods:

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);
[
  { 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' }
]

Comparison

Method Time Complexity Readability Memory Usage
Nested Loops O(m × n) High Low
Map + Reduce O(m × n) Medium Medium (spread operator creates copies)

Time and Space Complexity

Both methods have the same time complexity of O(m × n), where m is the length of the first array and n is the length of the second array. The nested loop approach has better space complexity as it doesn't create intermediate arrays like the functional approach does with the spread operator.

Conclusion

Creating Cartesian products in JavaScript can be achieved through nested loops for simplicity or functional methods for a more declarative style. Choose the approach that best fits your project's coding style and performance requirements.

Updated on: 2026-03-15T23:19:00+05:30

592 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements