Open In App

Set of pairs of numbers in JavaScript

Last Updated : 20 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • Make an array with five values and initialize it in a variable named nums.
  • Iterate loop from 0 to array length. For finding array length use nums.length where nums is an array.
  • Then, inside the body of the first loop use another loop this loop is iterating from i+1 to nums.length.
  • Then, inside the body of the second array write console.log() for printing the Set of pairs of the numbers.

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

Javascript




// 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

  • Make an array with four numbers and initialize in a variable.
  • Make a function named printPairs with parameters nums, I, and j. Then inside the body of the function check if i >=nums.length where nums is an array.
  • Check again if j>=nums.length and if the condition is true then inside body there is a calling a same function as printPairs(nums, i+1, i+2).
  • Then print using console.log() method of Set of pairs of numbers.
  • Call the function with three arguments as printPairs(nums, 0, 1).

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

Javascript




//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


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads