1

I got this array:

[
name1, 
[email protected],
[email protected],
[email protected],
name2,
[email protected],
name3,
name4,
[email protected],
[email protected],
[email protected],
[email protected],
[email protected],
]

From that array I need to parse it and create an array like the following:

[
{ dlName: < element without @ > , members: [<elements with @ >]}, 
{ dlName: < element without @ > , members: [<elements with @ >]}, 
{ dlName: < element without @ > , members: [<elements with @ >]}
]

example:

[
  HR,
  [email protected],
  [email protected],
  [email protected],
  cyber,
  [email protected],
  [email protected],
  accessibility,
  accounting,
   [email protected],
   [email protected]
]

output:

[
{ dlName: HR , members: [[email protected],[email protected],[email protected],]}, 
{ dlName: cyber , members:[[email protected],[email protected],]}, 
{ dlName: accesibility , members: []},
{ dlName: accounting , members: [[email protected],[email protected]]}
]

How can I get this output, everything I tried does not work for me needs.

Thanks in advance

2
  • a bit unclear can you give the expected output based on the input provided Commented Jun 29, 2022 at 14:41
  • I just update it with examples Commented Jun 29, 2022 at 14:52

1 Answer 1

2

You could reduce the array by having a look to the strings.

If you got an '@' add the string to the last object to members, otherose add a new object to the result set.

const
    data = ['name1', '[email protected]', '[email protected]', '[email protected]', 'name2', '[email protected]', 'name3', 'name4', '[email protected]', '[email protected]', '[email protected]', '[email protected]', '[email protected]'],
    result = data.reduce((r, v) => {
        if (v.includes('@')) r[r.length - 1].members.push(v);
        else r.push(({ dlName: v, members: [] }));
        return r;
    }, []);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

1 Comment

this is almost perfect, I forgot to mention there are some undefined values in there too and it changes a bit the output. I will try to tinkle with your solution. I will mark it as accepted as it solves the problem I asked for. Thanks!

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.