Skip to main content
3 of 4
Guessed langauge
Toby Speight
  • 81.8k
  • 14
  • 101
  • 309

Combinations of elements in array

I wrote this code to get all possible arrangements for an array containing 3 elements:

let a = ["A", "B", "C"];
let b = [];

function change(A) {
    let x = [];
    for (let i = 0; i < A.length; i++) {
        x.push(A[i]);
    }
    for (let i = 0; i < x.length; i++) {
        A[i] = x[i + 1];
        if (i == (x.length - 1)) {
            A[i] = x[0];
        }
    }
}

function combinations() {
    for (let i = 0; i < a.length; i++) {
        b.push([a[0], a[1], a[2]]);
        b.push([a[0], a[2], a[1]]);
        change(a);
    }
    console.log(b);
}
combinations();

How can I write this more concisely, and how is it possible to get all possible arrangements of an array consisting of more than 3 elements?

John
  • 49
  • 4