Open In App

Set of pairs of numbers in JavaScript

To Access all sets of pairs of Numbers in an array, We need to access all possible pairs of numbers and need to apply conditions and other operations. In this article, we will see how to access a pair of numbers in JavaScript using different approaches. The first approach is Nested Loop and the second approach is the Recursion Approach.

Approach: Using Nested Loop

Example: In this approach, we are going to use a nested loop means loop inside another loop to access pairs.




// Print set of pair of numbers
let nums = [1, 2, 3, 4, 5]
 
//Loop for first element
for (let i = 0; i < nums.length; i++) {
 
    //Loop for second element
    for (let j = i + 1; j < nums.length; j++) {
        console.log(`${nums[i]}, ${nums[j]}`);
    }
}

Output

1, 2
1, 3
1, 4
1, 5
2, 3
2, 4
2, 5
3, 4
3, 5
4, 5

Approach: Using Recursion

Example: In this approach, we are going to use Recursion means Function calling itself to access pairs.




//Recursion approach to access pairs in array
 
function printPairs(nums, i, j) {
 
    //Recursion break condition
    if (i >= nums.length) {
        return;
    }
    if (j >= nums.length) {
        printPairs(nums, i + 1, i + 2);
        return;
    }
 
    console.log(`${nums[i]}, ${nums[j]}`);
    printPairs(nums, i, j + 1);
}
 
let nums = [1, 2, 3, 4];
 
//Function call
printPairs(nums, 0, 1);

Output
1, 2
1, 3
1, 4
2, 3
2, 4
3, 4

Article Tags :