Split array into a string with commas

I have an output array variable ‘impairmentAreas’ with this content inside this ‘,Activities of Daily Living,Concentration,Social Functioning’

I need to make it look like this: ‘Activities of Daily Living, Concentration, Social Functioning’

if I use array.Join(’, '); I still get the first item with a comma before it.

Also, is there a way to make it so that the last item is split with an “and” rather than a comma?

I found this code but I can’t seem to make it work:

function Array.toString(array){
  return array
    .join(", ")
    .replace(/, ((?:.(?!, ))+)$/, ' and $1');
}

Current Drafts Code:

var p = Prompt.create();

p.title = "Psychological Impairment Areas";
p.isCancellable = true;
p.addButton('OK');

p.addSelect("impairmentAreas","Psychological Impairment Areas",["Activities of Daily Living", "Social Functioning", 'Concentration', 'Adaptation'],[""],true);

p.addPicker('ADL', 'Activities of Daily Living', [['Class 1: No Impairment', 'Class 2: Mild Impairment', 'Class 3: Moderate Impairment', 'Class 4: Marked Impairment', 'Class 5: Extreme Impairment']])

p.addPicker('socialFunctioning', 'Social Functioning', [['Class 1: No Impairment', 'Class 2: Mild Impairment', 'Class 3: Moderate Impairment', 'Class 4: Marked Impairment', 'Class 5: Extreme Impairment']])

p.addPicker('concentration', 'Concentration', [['Class 1: No Impairment', 'Class 2: Mild Impairment', 'Class 3: Moderate Impairment', 'Class 4: Marked Impairment', 'Class 5: Extreme Impairment']])

p.addPicker('adaptation', 'Adaptation', [['Class 1: No Impairment', 'Class 2: Mild Impairment', 'Class 3: Moderate Impairment', 'Class 4: Marked Impairment', 'Class 5: Extreme Impairment']])

if (p.show())	{

// Impairment Areas
var impairmentAreas = p.fieldValues['impairmentAreas'];
impairmentAreas.join(', ');

const impairment = {0:'Class 1: No Impairment', 1:'Class 2: Mild Impairment', 2:'Class 3: Moderate Impairment', 3:'Class 4: Marked Impairment', 4:'Class 5: Extreme Impairment'};

// Impairment Class Levels

let ADL = impairment[p.fieldValues['ADL']];
let socialFunctioning = impairment[p.fieldValues['socialFunctioning']];
let concentration = impairment[p.fieldValues['concentration']];
let adaptation = impairment[p.fieldValues['adaptation']];

var text = `With respect to catastrophic determination, it is our opinion that psychological impairment exists for Mr. XX and warrants a separate rating under Chapter 14, AMA Guides, 4th Edition. Mr. XX has Marked Impairment (Class 4) in ${impairmentAreas}. As such, Mr. XX would meet the catastrophic threshold for mental and behavioural impairments under Criterion 8 with at least one Marked (Class 4) impairments.

**Mental and Behavioural Disorders – AMA Guides Classification Table**

- Activities of Daily Living - ${ADL}
- Social Functioning - ${socialFunctioning}
- Concentration - ${concentration}
- Adaptation - ${adaptation}`

editor.setSelectedText (text);
}

You could remove the empty value from your array before joining, but the empty value is only there because of an error in the way you called p.addSelect. In the this line:

p.addSelect("impairmentAreas","Psychological Impairment Areas",["Activities of Daily Living", "Social Functioning", 'Concentration', 'Adaptation'],[""],true);

The [""] is creating a selected value of "" - an empty string. You want that to be an empty array, which is just []…so change that line to:

p.addSelect("impairmentAreas","Psychological Impairment Areas",["Activities of Daily Living", "Social Functioning", 'Concentration', 'Adaptation'],[],true);

Thank you for the clarification. I am almost there. I need to do two things, join strings with a comma and add an “and” before the last item.

Here is what I have that works:

var impairmentAreas = ["Activities of Daily Living", 'Concentration', 'Adaptation', "Social Functioning"];
var impairmentAreasSorted = impairmentAreas
    .join(", ")
	.replace(/, ((?:.(?!, ))+)$/, ' and $1');
console.log(impairmentAreasSorted);

Would this be better done with a function? I am still trying to learn how to write basic functions and not sure how would the above work with a function.

FWIW, a user from another forum kindly shared this excellent version of the function enList with test code. It should do what you’re asking for. Hope it helps.

(() => {
    "use strict";

    // enList :: [String] -> String
    const enList = xs => {
        const n = xs.length;
        const go = (m, ys) =>
            3 > m ? (
                0 === m ? (
                    ""
                ) : 1 === m ? (
                    ys[0]
                ) : `${ys[0]}, and ${ys[1]}`
            ) : `${ys[0]}, ${go(m - 1, ys.slice(1))}`;

        return 2 !== n ? (
            go(n, xs)
        ) : `${xs[0]} and ${xs[1]}`;
    };

    const main = () =>
        inits(enumFromTo(1)(4).map(str))
        .map(enList)
        .join("\n");


    // --------------------- GENERIC ---------------------

    // enumFromTo :: Int -> Int -> [Int]
    const enumFromTo = m =>
        n => Array.from({
            length: 1 + n - m
        }, (_, i) => m + i);


    // inits :: [a] -> [[a]]
    // inits :: String -> [String]
    const inits = xs =>
        // All prefixes of the argument,
        // shortest first.
        [].concat(xs)
        .map((_, i, ys) => ys.slice(0, 1 + i));

    // str :: a -> String
    const str = x =>
        Array.isArray(x) && x.every(
            v => ("string" === typeof v) && (1 === v.length)
        ) ? (
            // [Char] -> String
            x.join("")
        ) : null === x ? (
            "null"
        ) : x.toString();

    return main();
})();
1 Like