获取数组中元素的所有组合方式

代码

/**
 * 获取 words 成员的所有 组合 方式
 * @param {(string | number)[]} words
 * @return {(string|number)[][]}
 */
function combine (words) {
  const list = []
  words.forEach((word, idx) => {
    const restWords = [...words.slice(0, idx), ...words.slice(idx + 1)]
    if (!restWords.length) { // 最后一位了
      list.push([word])
    } else {
      const groups = combine(restWords)
      groups.forEach(group => {
        list.push([word, ...group])
      })
    }
  })
  return list
}

输出

combine(['A', 'B', 'C'])
[
  [ 'A', 'B', 'C' ],
  [ 'A', 'C', 'B' ],
  [ 'B', 'A', 'C' ],
  [ 'B', 'C', 'A' ],
  [ 'C', 'A', 'B' ],
  [ 'C', 'B', 'A' ]
]

作者:暗恋桃花源丫
本人web前端小白,只是用博客作为笔记!
转载的文章,如有侵权24小时内删除!

posted @   暗恋桃埖源  阅读(44)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 地球OL攻略 —— 某应届生求职总结
· 提示词工程——AI应用必不可少的技术
· Open-Sora 2.0 重磅开源!
· 字符编码:从基础到乱码解决
点击右上角即可分享
微信分享提示