DEV Community

loading...

Discussion on: Daily Challenge #66- Friend List

Collapse
ynndvn profile image
La blatte

Lets do it:

s
.split(';')
.map(n=>n.split(':').reverse().join(':'))
.sort()
.map(n=>`(${n.split(':')[0]}, ${n.split(':')[1]})`.toUpperCase())
.join``

It's pretty straightforward:

  • split(';') gets us all Name:Surname
  • .map(n=>n.split(':').reverse().join(':')) reverses them to be Surname:Name
  • .sort() sorts them alphabetically
  • .map(n=>(${n.split(':')[0]}, ${n.split(':')[1]}).toUpperCase()) reformats every name (uppercase it, place parentheses and commas)
  • The last step is equivalent to .join(''), which transforms the name array to an output string

Here is the output:

"Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill"
.split(';')
.map(n=>n.split(':').reverse().join(':'))
.sort()
.map(n=>`(${n.split(':')[0]}, ${n.split(':')[1]})`.toUpperCase())
.join``;


// "(CORWILL, ALFRED)(CORWILL, FRED)(CORWILL, RAPHAEL)(CORWILL, WILFRED)(TORNBULL, BARNEY)(TORNBULL, BETTY)(TORNBULL, BJON)"
Collapse
blindfish3 profile image
Ben Calder

Same but different:

  const s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
  return s.toUpperCase().split(';')
          .map(name => name.split(':').reverse())
          .sort()
          .reduce((accumulator, name) => ( accumulator += `(${name[0]}, ${name[1]})`), "");

You don't need the arbitrary join(':') after reverse() since sort() coerces the nested arrays to strings for you. That means you can avoid having to split again later.

But Amin is right:

  const s = "Fred:Corwill;Wilfred:Corwill;Barney:Tornbull;Betty:Tornbull;Bjon:Tornbull;Raphael:Corwill;Alfred:Corwill";
  return s.toUpperCase().split(';')
             .map(name=> `(${name.split(':')[1]}, ${name.split(':')[0]}`)
             .sort()
             .join('');
Collapse
ynndvn profile image
La blatte

That's way shorter! Thanks a lot for the input

Collapse
aminnairi profile image
Amin

I see we got a similar solution you and I!

I think you can even shorten (if I'm not mistaken) your solution by reducing one .map down and doing like me the surrounding in your first call to the .map method!

Should such a .surround method exist in String.prototype? I have came accross several cases where I would need it like in a WYSIWYG editor. But I don't want to risk proposing such a method to the community haha!

Good take btw!