'Looping Array Recursively to Create Object

I'm seriously struggling to solve this algorithm. I know the solution will be recursive, but i'm stumped on how to solve this problem. Feel free to take a crack at it. Thank you

Problem: ['a','b','c',['d','e','f',['g','h']], [i, j, k]]

Output:

{
  a: true,
  b: true,
  c: true,
  d: {
   e: true,
   f: true,
   g: {
     h: true
   }
  },
   i: {
     j: true,
     k: true
   }
}



Solution 1:[1]

You could use Object.fromEntries and feed it key/value pairs. When the "key" happens to be an array, use the first element as key, and perform recursion on the remainder of the array to get the value part:

const toObject = arr =>
    Object.fromEntries(arr.map(item => Array.isArray(item)
        ? [item[0], toObject(item.slice(1))]
        : [item, true]
    ));

const arr = ["a", "b", "c", ["d", "e", "f", ["g", "h"]], ["i", "j", "k"]];
const result = toObject(arr);
console.log(result);

Solution 2:[2]

Using Array#reduce:

const convert = (arr = []) =>
  arr.reduce((acc, e) => {
    if (Array.isArray(e)) {
      const [k, ...sub] = e;
      acc[k] = convert(sub);
    } else {
      acc[e] = true;
    }
    return acc;
  }, {});

console.log(
  convert(["a", "b", "c", ["d", "e", "f", ["g", "h"]], ["i", "j", "k"]])
);

Solution 3:[3]

In Ruby (think pseudo-code).

def recurse(arr)
  arr.each_with_object({}) do |e,h|
    case e
    when String
      h[e.to_sym] = true
    else # Array
      h[e.first.to_sym] = recurse(e.drop(1))
    end
  end
end

Suppose (slightly changed from example in question)

arr = ['a','b','c',['d','e','f',['g','h', ['m', 'n']]], ['i', 'j', 'k']]

Then

recurse arr
  #=> {
  #     :a=>true,
  #     :b=>true,
  #     :c=>true,
  #     :d=> {
  #       :e=>true,
  #       :f=>true,
  #       :g=>{
  #       :h=>true,
  #         :m=>{
  #         :n=>true
  #       }
  #     }
  #   },
  #   :i=>{
  #     :j=>true,
  #     :k=>true
  #   }
  # }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 trincot
Solution 2 Majed Badawi
Solution 3 Cary Swoveland