DEV Community

Divyajyoti Ukirde
Divyajyoti Ukirde

Posted on • Updated on


Easy peasy formatting list of names

Given an array containing hashes of names.
You have to return a string formatted as a list of names separated by commas except for the last two names, which should be separated by &.

formatList([ {name: 'Dave'}, {name: 'Alex'}, {name: 'Marge'} ])
// returns 'Dave, Alex & Marge'
Enter fullscreen mode Exit fullscreen mode

Here's a single line solution, regex peeps

let formatList = (names) => =>', ').replace(/(.*),(.*)$/, "$1 &$2");
Enter fullscreen mode Exit fullscreen mode

But this is the most clever solution, I could never think of:

let formatList = (names) => {
  let a = =>;
  let name = a.pop();
  return a.length ? a.join(", ") + " & " + name : name || "";
Enter fullscreen mode Exit fullscreen mode

I could think of using reduce, forEach and other looping methods using if else. reduce does a pretty great job itself.

let formatList = (names) => {
  return names.reduce((prev, curr, i, arr) => {
    return prev + + (i < arr.length - 2 ? ', ' : i == arr.length - 2 ? ' & ' : '');
  }, '');
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

11 Tips That Make You a Better Typescript Programmer


1 Think in {Set}

Type is an everyday concept to programmers, but it’s surprisingly difficult to define it succinctly. I find it helpful to use Set as a conceptual model instead.

#2 Understand declared type and narrowed type

One extremely powerful typescript feature is automatic type narrowing based on control flow. This means a variable has two types associated with it at any specific point of code location: a declaration type and a narrowed type.

#3 Use discriminated union instead of optional fields


Read the whole post now!