Open In App

JavaScript – Find All The Combinations of Array Values

Last Updated : 15 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Combinations refer to subsets of a given array, where the order of elements does not matter. For example, given an array [1, 2, 3], the possible combinations include:

  • Single-element combinations: [1], [2], [3]
  • Two-element combinations: [1, 2], [1, 3], [2, 3]
  • All three elements: [1, 2, 3] 

Here are the different methods to find all the combinations of array values in JavaScript

1. Using Recursive Approach

Recursion is used to solve the problem. The base condition is When the length of the array reduces to one then return that element of the array.

JavaScript
function get(arr) {
    const res = [];

    function help(curr, remain) {
        if (remain.length === 0) {
            if (curr.length > 0) {
                res.push(curr);
            }
            return;
        }

        help([...curr, remain[0]], remain.slice(1));

        help(curr, remain.slice(1));
    }

    help([], arr);
    return res;
}


//Driver Code Starts{
const inp = [1, 2, 3];
console.log(get(inp));
//Driver Code Ends }

Output
[ [ 1, 2, 3 ], [ 1, 2 ], [ 1, 3 ], [ 1 ], [ 2, 3 ], [ 2 ], [ 3 ] ]

In this example

  • The help function recursively generates all subsets by either including or excluding each element from the array.
  • It makes two recursive calls: one that includes the current element and one that excludes it, processing until all elements are considered.
  • When the recursion finishes, all non-empty subsets are collected in the res array and returned.

2. Using Bitmasking/Iterative method for Combinations

Bitmasking/ Iterative method provides an alternative approach to generating combinations.

JavaScript
function get(arr) {
    const res = [];
    const total = Math.pow(2, arr.length);

    for (let i = 1; i < total; i++) {
        const comb = [];
        for (let j = 0; j < arr.length; j++) {
            if (i & (1 << j)) {
                comb.push(arr[j]);
            }
        }
        res.push(comb);
    }
    return res
}

const inp = [1, 2, 3];
//Driver Code Starts{
console.log(get(inp));
//Driver Code Ends }

Output
[ [ 1 ], [ 2 ], [ 1, 2 ], [ 3 ], [ 1, 3 ], [ 2, 3 ], [ 1, 2, 3 ] ]

In this example

  • The get function generates all non-empty subsets by using bit manipulation, where each bit in the binary representation of numbers determines whether to include an element from the array.
  • The outer loop iterates through all possible combinations (from 1 to 2^n – 1), and the inner loop checks each bit of the number to decide which elements to include.
  • Each subset is added to the res array, which is returned after processing all combinations.


Next Article

Similar Reads