JSFiddle - React, Tailwind, and code Playground

by Pankaj Kargirwar

JavaScript

function generateCombinations(array, length, property) {
    const result = [];

    function combine(startIndex, combination) {
        if (combination.length === length) {
            result.push(combination.slice()); // Push a copy of the combination to the result
            return;
        }

        for (let i = startIndex; i < array.length; i++) {
            combination.push(array[i]); // Include the current element in the combination
            combine(i + 1, combination); // Recursively combine remaining elements
            combination.pop(); // Backtrack: remove the last element to try the next one
        }
    }

    combine(0, []); // Start combination generation from index 0 with an empty combination
    return result.map(combination => combination.map(item => structuredClone(item)));
}

// Example usage:
const array = [
    { id: 1, name: 'Alice' },
    { id: 2, name: 'Bob' },
    { id: 3, name: 'Charlie' }
];
const length = 2;
const property = 'name';
const combinations = generateCombinations(array, length, property);
console.log(combinations);