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

Cách tìm tất cả tập con của một tập hợp trong JavaScript?


Để tìm tất cả tập con của một tập hợp, dùng reduce() kết hợp map() trong JavaScript. Ví dụ: tập [8,9] tìm các tập con.

Ví dụ

const findAllSubsetsoOfGivenSet = originalArrayValue => originalArrayValue.reduce( (givenSet, setValue) => givenSet.concat( givenSet.map(givenSet => [setValue,...givenSet]) ), [[]] ); console.log(findAllSubsetsoOfGivenSet([8,9]));

Chạy: node fileName.js. File demo36.js.

Kết quả

PS C:\Users\Amit\JavaScript-code> node demo36.js [ [], [ 8 ], [ 9 ], [ 9, 8 ] ]