Create simple text string from array typescript


I have some array of strings like this

const doc = ['TEST', 'TEST1','TEST2']

What I need is to make function that I will create simple string from doc, that will have some different text.

  1. If there is just one array member to show

    const text = ‘There is 1 doc TEST1’;

  2. If there is two array member to show

    const text = ‘There is doc TEST1 and TEST2’;

  3. If there is more than twoarray member to show, of course this doc array can have more than 3 array members, but this is just example

    const text = ‘There is doc TEST1, TEST2 and TEST3’;

Thanks in advance I don’t know how even to start


function toSentence(arr){
  if(arr.length===1)return `There is 1 doc ${arr[0]}`;
  const last = arr.pop();
  const others=arr.join(", ");
  return `There are docs ${others} and ${last}`

Answered By – Andrea

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published