0

I have an array like this:

initialArray = ["a", "b", "c". "d.e", "d.e.f", "d.e.g", "d.h.i", "d.h.j"]

But I want this array like this or the closest as possible:

finalArray: [
                    { "a": [] },
                    { "b": [] },
                    { "c": [] },
                    { "d": [
                            { "e": [ "f", "g" ] },
                            { "h": [ "i", "j" ] }
                        ] },
                ]

The values of initialArray are randomly assigned. The values and the length of the comma separated strings can be changed (there can be more or less letters in those strings), so that I need a general idea to build that finalArray. I'd really be appreciated if someone can help me. Thank you so much.

2
  • How do you get from initialArray to finalArray? Commented Dec 23, 2019 at 19:36
  • Are you sure? That array with objects with only one key makes little sense ... Commented Dec 23, 2019 at 19:45

3 Answers 3

2

You can use split in forEach loop to create an array for each path and then use reduce method to create nested structure.

const data = ["a", "b", "c", "d.e", "d.e.f", "d.e.g", "d.h.i", "d.h.j"]

const result = []
const level = { result }

data.forEach(str => {
  str.split('.').reduce((r, e) => {
    if (!r[e]) {
      r[e] = {result: []}
      r.result.push({[e]: r[e].result})
    }
    return r[e]
  }, level)
})

console.log(result)

Sign up to request clarification or add additional context in comments.

Comments

0

It looks like a left-skewed binary tree or a linked list kind of problem. If there is a dot after the current character, use that as an indicator that node .next() or .left() exists. You'd need to manually check for duplicates, i.e, check if the current char, e.g, 'e': finalArray->d->e exists, if so, just append to its values, otherwise, create a new array. That's how I'd approach it.

Comments

0

I think you may need to create an object. But I don't know what you really want to do...

var obj = new Object();

// add a key named myKey with value "myValue"
obj["myKey"] = "myValue";  

// add a dynamic key with a dynamic value
var key = "something", 
val = "something"; 

obj[key] = val;

// read value 
val = obj["myKey"];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.