Answer the question
In order to leave comments, you need to log in
How to correct the cycle?
It is necessary to save all possible combinations with variables, for example:
There is a, b , c
It should turn out like this
combo 1: a arr[0] = [a]
combo 2: b arr[1] = [b]
combo 3: c arr[2 ] = [c]
combo 4: ab arr[3] = [a, b]
combo 5: ac arr[4] = [a, c]
combo 6: bc arr[5] = [b, c]
combo 7: abc arr[6] = [a, b, c]
function nearest(arr) {
var len = arr.length
, i
, bit
, n = Math.pow(2, len)
, result = []
;
for( i = 1; i < n; i++) {
for( bit = 0; bit < len; bit++) {
if( i & (1 << bit)) {
result.push(arr[bit]);
}
}
}
Answer the question
In order to leave comments, you need to log in
Create a subarray in the outer loop, fill it in the inner loop, then add it to result.
https://jsfiddle.net/mh0tq8hd/
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question