I have Person and group names
Person :
Robert Smith
David Smith
James Johnson
William
if i use this code
if(Name.split(",").length === 1)
return Name.trim().split(" ").map(x => x[0]).reduce((acc, curr) => acc + curr)
else
return ''
Output is
- RS
- DS
- JJ
but in my second scenario there are sets of names
like
Robert Smith,David SmithJames Johnson,Robert Smith
in this case if any comma is found i want to return RD in first case and in second case JS
>Solution :
Your question is not clear, I assume you need to get the initial of the first and last name in the first scenario and get the initial of each name in the second scenario.
Check whether the following solution helps,
const scenario1 = "Robert Smith";
const scenario2 = "Robert Smith,David Smith";
function getInitial(data) {
const chunks = data.split(",");
if ( chunks.length > 1) {
const initials = [];
chunks.forEach(chunk => initials.push(chunk[0]));
return initials.join('');
} else {
const [fname, lname] = chunks[0].split(' ');
return `${fname[0]}${(lname ? lname[0] : '')}`;
}
}
console.log(getInitial(scenario1))
console.log(getInitial(scenario2))