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.
If there is just one array member to show
const text = 'There is 1 doc TEST1';
If there is two array member to show
const text = 'There is doc TEST1 and TEST2';
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
CodePudding user response:
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}`
}
CodePudding user response:
You can use join for all but the last entry, and add the last entry with "and". I suppose for an empty array you would return something like "there is no doc":
function makePhrase(arr) {
if (arr.length === 0) return "There is no doc";
if (arr.length === 1) return "There is 1 doc " arr;
return "There is doc "
arr.slice(0, -1).join(", ") " and " arr.at(-1);
}
console.log(makePhrase([]));
console.log(makePhrase(["test1"]));
console.log(makePhrase(["test1", "test2"]));
console.log(makePhrase(["test1", "test2", "test3"]));
console.log(makePhrase(["test1", "test2", "test3", "test4"]));
