2

Hello I have a little problem I have arrays like this:

const arrays = {
    1: [c, u, g],
    2: [c, u],
    3: [c, u ,f],
    4: [c, g],
    5: [m, c, g],
    6: [u, m]
}

Values in each array are unique. I would like to convert it to an object like this:

const object = {
  c: {
    u: {
      g: {
        ends: 1
      },
      f: {
        ends: 3
      }
      ends: 2
    },
    g: {
      m: {
        ends: 5
      }
      ends: 4
    }
  },
  u: {
    m: {
      ends: 6
    }
  }
}

Is it possible ? And if so could you give me hint, piece of code or any other type of answer I'm hard stuck here.

7
  • Have you considered transforming the arrays to an object of wanted structure first and then converting that object to a JSON? Commented Jul 27, 2020 at 13:06
  • I did, but the problem is I need it to be properly sorted like shown in the example. The 'c' has to be obviously the most appeared value, then in the arrays with 'c' in them it has to look for new most appeared value in arrays with 'c' in them Commented Jul 27, 2020 at 13:09
  • Why is [m, c, g] missing from the output? Commented Jul 27, 2020 at 13:11
  • i'm not sure I understand the reasoning behind your input and wanted output, like for example you have m in g, but m is before c. You may have to loop 2 times, one first time to order by occurences count ? Commented Jul 27, 2020 at 13:13
  • @adiga I think it became c.g.m it's also what is puzzling me Commented Jul 27, 2020 at 13:15

1 Answer 1

1

You can loop through the entries of the object. Then reduce each value array and create nested object in each iteration. The reduce returns the final nested object. So, add an ends property here.

If you don't want sorted nested path, you can skip the sort bit

const input = {
  1: ["c", "u", "g"],
  2: ["c", "u"],
  3: ["c", "u", "f"],
  4: ["c", "g"],
  5: ["m", "c", "g"],
  6: ["u", "m"]
}

const output = {};

for (const [n, paths] of Object.entries(input)) {
  paths
    .sort()
    .reduce((acc, path) => (acc[path] = acc[path] || {}), output)
    .ends = +n
}

console.log(output)

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

2 Comments

Thank you really much. I can make it work with this answer and a few tweaks. Thanks again! But if someone has the same problem this won't solve everything you still need to sort them by times it appears in all of the arrays.
@Xy77 Do you want to sort individual arrays based on how many times each of the strings appear in the overall object?

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.