About javascript looping logic

Let car = [‘c’,‘a’,‘r’];

Expected result: [‘c’,‘ca’,‘cr’,‘car’,‘a’,‘ar’,‘r’]

How to solve this by forloop in js?

Thanks in advance

What have you tried so far?

Gonna be honest, the answer to this using for is somewhat eluding me… at least, in the expected result order.

Solved . . .


Somehow Virgil comes to mind on looking at that.

“Beware of Greeks bearing gifts.” - Virgil.


I have just used split to seperate it and concat

I want to know if it’s possible using forloop


I can get to a point where it would give [“c”,“a”,“r”,“ca”,“cr”, “ar”,“car”] in a relatively non-specific for formation, but not in the order that was given.

Essentially, OP would be hardcoding a recursive operation though, which is the better solution.

Order is not an issue

Less ‘if’ statements now . . . . .

OP, is there an actual problem you are trying to solve by doing this?


Well then this should do the trick…

function powerset ([head, ...tail]) {
  if (!head) {
    return []

  if (!tail.length) {
    return [head]

  const tailResults = powerset(tail)

  return [head, ...tailResults, ...tailResults.map(
    result => head + result)]

console.log(powerset(['c', 'a', 'r'])) // ['c', 'a', 'r', 'ar', 'ca',  'cr', 'car']

BTW does anyone know the technical term for this?

Edit: Thx @rpkamp! :-)

That will be combinations. The other one commonly seen is permutations.

[Edit: Cunningham’s Law to the rescue once again!
“the best way to get the right answer on the internet is not to ask a question; it’s to post the wrong answer.”]

1 Like

It’s the Power set of the set (“c”, “a”, “r”)


strictly speaking if it was a power set it would also contain "", (a power set contains 2^n elements, so an input set of size 3 should have a power set of size 8) but thats a quibble. :stuck_out_tongue:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.