如何在JavaScript中查找集合的所有子集? [英] How to find all subsets of a set in JavaScript?

查看:119
本文介绍了如何在JavaScript中查找集合的所有子集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要获取数组的所有可能子集.

I need to get all possible subsets of an array.

说我有这个:

[1, 2, 3]

我怎么得到这个?

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

我对所有子集都感兴趣.对于特定长度的子集,请参考以下问题:

I am interested in all subsets. For subsets of specific length, refer to the following questions:

  • 查找大小为n的子集: 1 2
  • 查找大小大于1的子集: 1
  • Finding subsets of size n: 1, 2
  • Finding subsets of size > 1: 1

推荐答案

这是另一种非常优雅的解决方案,没有循环或递归,仅使用map和reduce数组本机函数.

Here is one more very elegant solution with no loops or recursion, only using the map and reduce array native functions.

const getAllSubsets = 
      theArray => theArray.reduce(
        (subsets, value) => subsets.concat(
         subsets.map(set => [value,...set])
        ),
        [[]]
      );

console.log(getAllSubsets([1,2,3]));

这篇关于如何在JavaScript中查找集合的所有子集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆