Oğuz Öztınaz
Oğuz Öztınaz

Reputation: 157

How to create an object array with child items without duplicated values in JavaScript

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.

Upvotes: 0

Views: 74

Answers (3)

Peyu
Peyu

Reputation: 431

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

Upvotes: 0

Nenad Vracar
Nenad Vracar

Reputation: 122047

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)

Upvotes: 2

suntzu
suntzu

Reputation: 65

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.

Upvotes: 0

Related Questions