Higeath Higeath - 5 months ago 17
Javascript Question

Subtracting specific last word from map

I have company names that I loop through and create abbreviations using the code below

dataset.nodes.forEach(d => {d.name = d.fullName.split(' ').map(w => w[0]).join('')});


Lloyds banking group PLC would be an example of a company and I would like to check if the last word is PLC/plc/p.l.c. and delete it before creating abbreviation because right now the abbreviation of this company would be LBGP and i would want it to be LBG

data:

var dataset = {"nodes":[{"fullName":"Anglo American plc"},{"fullName":"Whitbread PLC"}],"edges":[{"source":0,"target":29,"officers":["MEDORI, Rene"]},{"source":0,"target":30,"officers":["GROTE, Byron Elmer"]},{"source":0,"target":31,"officers":["GROTE, Byron Elmer"]},{"source":1,"target":13,"officers":["BASON, John George"]},{"source":1,"target":18,"officers":["HAUSER, Wolfhart Gunnar, Dr"]},{"source":1,"target":27,"officers":["SINCLAIR, Charles James Francis"]},{"source":2,"target":14,"officers":["COURT, Annette Elizabeth"]},{"source":3,"target":11,"officers":["GREEN, Andrew James"]},{"source":3,"target":12,"officers":["PUSEY, Stephen Charles"]},{"source":3,"target":15,"officers":["KENNEDY, Christopher John"]},{"source":3,"target":24,"officers":["CHAMBERS, Stuart John"]},{"source":3,"target":31,"officers":["CHAMBERS, Stuart John"]},{"source":3,"target":32,"officers":["KENNEDY, Christopher John"]},{"source":4,"target":8,"officers":["BARKER, Glyn"]},{"source":4,"target":12,"officers":["WHEWAY, Jonathan Scott"]}]};

Answer

After the split, test the last element against a regexp and then continue with the map:

omits = /p\.?l\.?c\.?/i;

dataset.nodes.forEach(d => {
  const parts = d.fullName.split(' ');
  if (omits.test(parts[parts.length-1])) parts.pop();
  d.name = parts . map(w => w[0]).join('')});
});