Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> JavaScript

Tạo tất cả hoán vị có thể của mảng trong JavaScript

Cho mảng số nguyên khác nhau, trả về tất cả hoán vị có thể.

Ví dụ: [1, 2, 3] → 6 hoán vị.

Ví dụ

const arr = [1, 2, 3]; 
const findPermutations = (arr = []) => { 
  let res = []; 
  const helper = (arr2) => { 
    if (arr2.length == arr.length) return res.push(arr2); 
    for(let e of arr) 
      if (!arr2.includes(e)) 
        helper([...arr2, e]); 
  }; 
  helper([]); 
  return res; 
}; 
console.log(findPermutations(arr));

Kết quả

Kết quả in ra console:

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