Home > database >  Looping Array Recursively to Create Object
Looping Array Recursively to Create Object

Time:03-03

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
   }
}

CodePudding user response:

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);

CodePudding user response:

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"]])
);

CodePudding user response:

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
  #   }
  # }
  • Related