I got this array:
[
name1,
email1@name1.com,
email2@name1.com,
email3@name1.com,
name2,
email1@name2.com,
name3,
name4,
email1@name4.com,
email2@name4.com,
email3@name4.com,
email4@name4.com,
email5@name4.com,
]
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,
someonefks@name.com,
fjkdafaldksjh@name.com,
sfafafads@name.com,
cyber,
fakdjfnakj@name.com,
fdsfasfasds@name.com,
accessibility,
accounting,
dasaasas@name.com,
klhdaflkaa@name.com
]
output:
[
{ dlName: HR , members: [someonefks@name.com,fjkdafaldksjh@name.com,sfafafads@name.com,]},
{ dlName: cyber , members:[fakdjfnakj@name.com,fdsfasfasds@name.com,]},
{ dlName: accesibility , members: []},
{ dlName: accounting , members: [dasaasas@name.com,klhdaflkaa@name.com]}
]
How can I get this output, everything I tried does not work for me needs.
Thanks in advance
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', 'email1@name1.com', 'email2@name1.com', 'email3@name1.com', 'name2', 'email1@name2.com', 'name3', 'name4', 'email1@name4.com', 'email2@name4.com', 'email3@name4.com', 'email4@name4.com', 'email5@name4.com'],
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; }