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
CodePudding user response:
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; }