Find Number Combinations in JavaScript

Beginner
⏱️ 10 min read
📚 Updated: May 2026
🎯 2 Code examples + Try it
Nested loops

What you’ll learn

  • How to print all orderings of three numbers using three loops.
  • How to print each unordered pair from an array once using j > i.
  • Permutation vs combination in simple words.

Overview

This page shows two patterns: permutations of three values (order matters) and pair combinations from four values (order ignored).

Live preview

Live result
Press “List orderings”.

📜 Pseudocode

Pseudocode
// Permutations of 3 values
for i in 0..2:
  for j in 0..2:
    for k in 0..2:
      if i, j, k are all different:
        print arr[i], arr[j], arr[k]

// Combinations of 2 from n
for i in 0..n-2:
  for j in i+1..n-1:
    print arr[i], arr[j]
1

All orderings of three numbers

JavaScript
const arr = [1, 2, 3];
const lines = [];

lines.push("All orderings (permutations) of the three numbers:");

for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    for (let k = 0; k < 3; k++) {
      if (i !== j && j !== k && i !== k) {
        lines.push(arr[i] + " " + arr[j] + " " + arr[k]);
      }
    }
  }
}

console.log(lines.join("\n"));
Try it Yourself
2

All pairs from four numbers

JavaScript
const arr = [10, 20, 30, 40];
const lines = [];

lines.push("All unordered pairs (choose 2 from 4):");

for (let i = 0; i < arr.length; i++) {
  for (let j = i + 1; j < arr.length; j++) {
    lines.push(arr[i] + " " + arr[j]);
  }
}

console.log(lines.join("\n"));
Try it Yourself

❓ FAQ

Permutation counts order (1,2,3 differs from 1,3,2). Combination ignores order (pair 10,20 is same as 20,10).
Each loop picks one position in a three-item ordering. Distinct index checks ensure no slot repeats.
It avoids duplicate pairs, so each unordered pair appears exactly once.
Exactly 6, because 3! = 6 permutations.
Yes. If input contains duplicates, printed permutations may look repeated even if indices differ.
Example 1 is constant for fixed size 3. Pair listing is O(n^2) for n items.

⏱️ Time and space complexity

ProgramTimeExtra space
Permutations for fixed size 3O(1)O(1)
All pairs from n valuesO(n^2)O(1) (excluding output)

Summary

  • Permutation: order matters, so three loops with distinct indices.
  • Combination pairs: use j = i + 1 to avoid duplicates.
Did you know?

In math, combination usually ignores order, while permutation counts different orders. This page shows both patterns using readable nested loops.

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful