Array returning unexpected result with addition ","

Vijay Baokar
Kilo Sage

Hi Folks,

I have defined few arrays which i am later storing into a field (,) separated this is almost achieved but getting extra "," before the value

 

Current result:

MFP - ,MC,GS,L6,G8,4L,C5,9C,IT,E0,
,BWC - ,MA,8A,6A,R4,4M,4X,PQ,LE,
,Consumer Printer (HPS) - ,L9,LG,E4,IR,2Q,

 

expected result:

 

MFP - MC,GS,L6,G8,4L,C5,9C,IT,E0
BWC - MA,8A,6A,R4,4M,4X,PQ,LE
Consumer Printer (HPS) - L9,LG,E4,IR,2Q

 

Note : MFP , BWC , Consumer Printer (HPS) these are Business area which has associated PL keys which are MC,GS,L6,G8,4L,C5,9C,IT,E0, or MA,8A,6A,R4,4M,4X,PQ,LE,

 

i am calling Script Include from on change client script, below is the SI:

 

var supProductMappingAjax1 = Class.create();
supProductMappingAjax1.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {

    getProductMapping: function() {

        var bsnGroup = this.getParameter('sysparm_businessGrp');
        var marketSub = this.getParameter('sysparm_marketSubSeg');

        gs.info("PS - Business Group is " + bsnGroup + "-" + marketSub);
        var arrSysIDs = [];
        var plKeys = [];
        var bg = [];
        var mss = [];

        var bs = new GlideRecord("cmdb_ci_service_business");
        bs.addQuery('sys_id', 'IN', bsnGroup);
        //  bs.get(bsnGroup);
        bg.push(bs.name);

        var so = new GlideRecord("service_offering");
        so.addQuery('sys_id', 'IN', marketSub);
         mss.push(so.name);
 
        var tempArray = [];
        for (var i = 0; i < bg.length(); i++) {
            for (var j = 0; j < mss.length(); j++) {

                var mapping = new GlideRecord("x_ihpp2_sup_scoped_sup_product_mapping");
                mapping.addQuery("business_group", bg[i]);
                mapping.addQuery("market_sub_segment", mss[j]);
                mapping.query();
                while (mapping.next()) {

                 
                    if (!tempArray.includes(mapping.india_classification.toString())) {
                        tempArray.push(mapping.india_classification.toString());
                        if (!arrSysIDs.includes(mapping.sys_id.toString())) {
                            arrSysIDs.push(mapping.sys_id.toString());
                        }
                    }
                    plKeys.push(mapping.india_classification.toString());
                }
            }
        }
        //   }
        gs.info("PS - mapping records are " + arrSysIDs);
        return arrSysIDs.join(',');
    },

    getPLkeys1: function() {

        var ind = this.getParameter('sysparm_indiaCLS');
        var bsg = this.getParameter('sysparm_bGroup');
        var mss = this.getParameter('sysparm_market');
        gs.info("PS - indiaclass is " + bsg + "--" + mss + "--" + ind);

        var bs = new GlideRecord("cmdb_ci_service_business");
        bs.get(bsg);
        var businessgroup = bs.name;

        var so = new GlideRecord("service_offering");
        so.get(mss);
        var marketsubseg = so.name;

        var arrSysIDs = [];
        var indArray = [];
        var plKeys = [];
        arrSysIDs.push(ind.split(','));
        gs.info("ind classification count " + arrSysIDs.length);

        for (var i = 0; i < arrSysIDs.length; i++) {

            var pm = new GlideRecord("x_ihpp2_sup_scoped_sup_product_mapping");
            pm.addQuery("sys_id", arrSysIDs[i]);
            pm.query();
            while (pm.next()) {
                indArray.push(pm.india_classification.toString());
            }
        }

        gs.info("ind classification array length - " + indArray.length + "-values- " + indArray);
        for (var j = 0; j < indArray.length; j++) {

            plKeys.push(indArray[j] + "  -  ");

            var pl = new GlideRecord("x_ihpp2_sup_scoped_sup_product_mapping");
            pl.addQuery("india_classification", indArray[j]);
            pl.addQuery("business_group", businessgroup);
            pl.addQuery("market_sub_segment", marketsubseg);
            pl.query();
            while (pl.next()) {

                plKeys.push(pl.pl_key.toString());

                gs.info("PS - classification " + indArray[j] + " PL Keys " + plKeys);
            }
            plKeys.push("\n");

        }

        gs.info("PS - pl keys are " + plKeys);
        return plKeys.join(',');

    },

    type: 'supProductMappingAjax1'
});
 

 

 

 

14 REPLIES 14

@Vijay Baokar Use @Ankur Bawiskar code that will work, I believe.

If my response was helpful, please mark it as correct and helpful.
Thank you.

Hello @Vijay Baokar,

 

I wouldn't give you a direct solution, but I would recommend considering some things:

  • bg.push(bs.name); -> I would recommend using this instead: bg.push(bs.getValue('name')); and everywhere in the code where you retrieve value of a field.
  • !tempArray.includes(mapping.india_classification.toString()) -> It's better to user ArrayUtil instead of array.includes
  • bs.get(bsg); -> Please add an IF condition to the GlideRecord get function, to check that the result exists, in order to avoid unexpected behavior.
  • var businessgroup = bs.name; -> Use the bs.getValue('name');
  • plKeys.push("\n"); -> Adding a new line to the array is not a good practice, I would use another approach.

 

MFP - ,MC,GS,L6,G8,4L,C5,9C,IT,E0,
,BWC - ,MA,8A,6A,R4,4M,4X,PQ,LE,

 

In my opinion, the reason of this strange look is, because you use the '\n' in the array. 

 

I would create the following structure:

 

 

{
  "MFP": [
    "MC",
    "GS",
    "..."
  ],
  "BWC": [
    "MA",
    "8A",
    "..."
  ],
  "Consumer Printer (HPS)": [
    "L9",
    "LG",
    "..."
  ]
}

 

 

If you have this structure of data it's easy to get the desired format from it.

gao
Tera Contributor

Hey,

 

To fix the issue of an extra comma appearing before the values in your comma-separated string, follow these steps:

  1. Remove Manual Addition of Commas:

    • Stop adding commas manually when pushing elements into your array. Instead, let the join(',') method handle the comma separation automatically.
  2. Use join(',') Method:
    After populating your array with the desired values, use the join(',') method to convert the array into a comma-separated string. 

  3. Clean the Array:

    • Ensure that all elements in your array are valid and not null, undefined, or empty strings. This prevents unexpected results when using join(',').
  4. Verify Parameters:

    • Check the parameters passed to your script to ensure there are no unintended empty values that might introduce extra commas.

Here comes the solution:

function getProductMapping() {
    // ... your original code ...

	var plKeys = [];
	while (mapping.next()) {
		var value = mapping.india_classification.toString();
		if (value) { // Only push if value is not empty or null
			plKeys.push(value);
		}
	}
	var result = plKeys.join(','); // This will create "MC,GS,L6,..."
	return result;
}



Ankur Bawiskar
Tera Patron
Tera Patron

@Vijay Baokar 

update script include as this

var supProductMappingAjax1 = Class.create();
supProductMappingAjax1.prototype = Object.extendsObject(global.AbstractAjaxProcessor, {

    getProductMapping: function() {
        var bsnGroup = this.getParameter('sysparm_businessGrp'); // comma-separated sys_ids
        var marketSub = this.getParameter('sysparm_marketSubSeg'); // comma-separated sys_ids

        gs.info("PS - Business Group is " + bsnGroup + "-" + marketSub);

        var bgArray = bsnGroup.split(',');
        var mssArray = marketSub.split(',');

        var finalResult = [];

        for (var b = 0; b < bgArray.length; b++) {
            var bs = new GlideRecord("cmdb_ci_service_business");
            if (!bs.get(bgArray[b])) continue;
            var businessGroup = bs.name;

            for (var m = 0; m < mssArray.length; m++) {
                var so = new GlideRecord("service_offering");
                if (!so.get(mssArray[m])) continue;
                var marketSubSeg = so.name;

                var mapping = new GlideRecord("x_ihpp2_sup_scoped_sup_product_mapping");
                mapping.addQuery("business_group", businessGroup);
                mapping.addQuery("market_sub_segment", marketSubSeg);
                mapping.query();

                var plKeys = [];
                while (mapping.next()) {
                    var key = mapping.pl_key.toString().trim();
                    if (key) plKeys.push(key);
                }

                // Remove duplicates
                plKeys = Array.from(new Set(plKeys));

                // Format line only if keys found
                if (plKeys.length > 0) {
                    var line = businessGroup + " - " + plKeys.join(',');
                    finalResult.push(line);
                }
            }
        }

        // Join all business-mapped lines with newline
        return finalResult.join('\n');
    },

    getPLkeys1: function() {
        var ind = this.getParameter('sysparm_indiaCLS');
        var bsg = this.getParameter('sysparm_bGroup');
        var mss = this.getParameter('sysparm_market');

        gs.info("PS - indiaclass is " + bsg + "--" + mss + "--" + ind);

        var bs = new GlideRecord("cmdb_ci_service_business");
        if (!bs.get(bsg)) return "";
        var businessgroup = bs.name;

        var so = new GlideRecord("service_offering");
        if (!so.get(mss)) return "";
        var marketsubseg = so.name;

        var indArray = ind.split(',').filter(function(item) {
            return item && item.trim();
        });

        var resultLines = [];

        for (var j = 0; j < indArray.length; j++) {
            var classification = indArray[j];
            var plKeys = [];

            var pl = new GlideRecord("x_ihpp2_sup_scoped_sup_product_mapping");
            pl.addQuery("india_classification", classification);
            pl.addQuery("business_group", businessgroup);
            pl.addQuery("market_sub_segment", marketsubseg);
            pl.query();

            while (pl.next()) {
                var key = pl.pl_key.toString().trim();
                if (key) plKeys.push(key);
            }

            // Remove duplicates
            plKeys = Array.from(new Set(plKeys));

            if (plKeys.length > 0) {
                var line = classification + " - " + plKeys.join(',');
                resultLines.push(line);
            }
        }

        return resultLines.join('\n');
    },

    type: 'supProductMappingAjax1'
});

If my response helped please mark it correct and close the thread so that it benefits future readers.

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader

@Ankur Bawiskar did you just update "getPLkeys1" function ?